我想逐行读取一个文件。做了类似的事情
void Parse (string filepath) {
ifstream sourceFile;
sourceFile.open(filepath);
for (string line; getline(sourceFile, line);) {
cout << "1" << endl;
cout << line << endl;
}
}
int main() {
Parse("C:\\test.txt");
getchar();
return 0;
}
然后将一些文本放入C:\test.txt
,但是当我运行时,我没有得到任何东西。为什么?甚至不是“1”。如果文件也不存在,我注意到也不异常(exception)。我想这是问题的征兆?
最佳答案
您必须手动检查成功/错误。试试 ifstream::good()
:
sourceFile.open(filepath);
if(!sourceFile.good()) {
// do something
如果不想手动检查,可以启用exceptions :
// call that before open()
sourceFile.exceptions ( ifstream::failbit | ifstream::badbit );
关于未读取 C++ 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013877/