在C++中取消设置变量时,文件打开(ifstream)不正确
Incorrect file opening (ifstream) when unsetting a variable in C++
我有以下C++程序。我打开一个文件(inputmincut.txt)并读取其内容。每当我评论n=0行时,程序就会崩溃。这对我来说毫无意义。会发生什么?
using namespace std;
ifstream input_file;
ofstream output_file;
int n;
void read()
{
int current=0;
int pos=0;
for(int i=1;i<=n;i++)
{
input_file>>current;
input_file>>pos;
while(pos!=-1)
input_file>>pos;
}
}
int main(int argc, char *argv[])
{
input_file.open("C:\Dev-Cpp\inputmincut.txt");
input_file>>n;
read();
input_file.close();
//n=0;
input_file.open("C:\Dev-Cpp\inputmincut.txt");
input_file>>n;
read();
input_file.close();
system("PAUSE");
return 0;
}
这是文本输入。
101 2 10-12 3 1-13 4 2-14 5 3-15 6 4-16 7 5-17 8 6-18 9 7-19 10 8-110 1 9-1
input_file.open("C:\Dev-Cpp\inputmincut.txt");
您确定在操作系统中使用"\"
而不是""
来表示路径吗!我认为你应该检查你的文件路径,并检查你是否打开了你的文件?
首先,您必须检查文件是否打开以进行读取。你可以写这样的东西:
void ropen(std::string const & path, std::ifstream & file)
{
file.open(path.c_str(), std::ios_base::in|std::ios_base::binary);
if(!file.is_open()) throw std::exception(
path +
std::string(": cannot open file for reading.")
);
}
然后:
int main(int argc, char *argv[])
{
std::istream file;
ropen(path,file);
std::line;
while(getline(file, line))
{
do something with your line
}
return 0;
}
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 特征 LLT 模块给出不正确的结果?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 如果语句逻辑不正确
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- 不正确的操作数类型 MSVC
- 数组填充了不正确的值
- 我是否不正确地集中了这些字符数组?
- 为什么除非我使用 cout,否则我的值不正确?
- 尝试使用 ifstream 读取数据后显示不正确的数字
- ifstream::read 不断返回不正确的值
- 在C++中取消设置变量时,文件打开(ifstream)不正确
- Ifstream::read总是返回不正确的值