如果我在我的代码中包含 if 测试,则会返回错误消息,我不确定为什么。 当它不被使用时,我的程序会陷入一个循环,永远不会到达文件的末尾。我不明白出了什么问题。
int countlines()
{
fstream myfile;
myfile.open("questions.txt", ios::in);
string contents;
int linenumber = 0;
//if (myfile.is_open())
// {
while (!myfile.eof())
{
getline( myfile, contents );
if (contents != "")
{
linenumber++;
}
}
cout << "there are " << linenumber << " lines.\n";
//}else {cout<<"Unable to get file.\n";}
myfile.close();
return(linenumber);
}
最佳答案
这是怎么回事,您的文件没有被打开。这就是 is_open
失败的原因。
然后,当您注释掉检查时,您将打破循环,因为您迭代不正确(请参阅我的评论)并且未检测到流故障(.eof()
将 永远不要在该流上为 true
。
确保文件位于正确的位置,并且可以访问。
关于C++ 文件处理,is_open 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9040651/