C++ 文件处理,is_open 返回错误

标签 c++ file-io

如果我在我的代码中包含 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/

相关文章:

c++ - 是否有字符串或数字的标识符?

linux - 在 ADA 中打开文件时出现段错误

c++ - 将二维 vector 保存到文本文件

vb.net - vb.net中如何避免文件被另一个进程使用

objective-c - 使用异步 NSURLConnection 获取本地文件是否过度?

C++ - thread_local 变量存储在哪里?

c++ - Windows 套接字错误 10013

c++ - 如果您始终将其存储在 shared_ptr 中,您的接口(interface)是否需要虚拟析构函数?

c++ - Cython 和 C++ 继承

python - 将字符串中的特定索引更改为相同的值 python