逐行读取文件的程序

热爱编程

我一直在尝试编写代码来逐行读取文件:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ifstream jin("Story.txt");
    // ins.open("Story.txt", ios::in);
    if (!jin)
    {
        cout << "File not opened" << endl;
        return 1;
    }
    else{
    char a[100];
    do
    {
        jin.getline(a, 100);
        cout << a << endl;
    } 
    while (!jin.eof());
    jin.close();
    return 0;
    }
}

但是,在 Windows 上的 Visual Studio Code 上执行此程序时,它表现为无限循环。有人能告诉我出了什么问题吗?

(我确定文件 Story.txt 存在,毫无疑问)

泰德·林格莫

std::istream::getline读取了 100-1 个字符(没有找到换行符\n)时,它将failbit在流上设置这可以防止进一步读取流(除非您重置该状态)。但是它没有设置,eofbit所以你现在有点不舒服。failbit阻止进一步的阅读和eof()回报false,因为eofbit没有设置-它会因此无限循环。

如果至少其中一行的Story.txt长度超过 99char秒,则会发生上述情况。

最简单的方法是使用 a std::stringandstd::getline代替:

#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream jin("Story.txt");
    if(!jin) {
        std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
        return 1;
    }

    std::string a;
    while(std::getline(jin, a)) {
        std::cout << a << '\n';
    }
    return 0;
}

如果你真的不想使用std::getlineand std::string,你可以,但它更难:

#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>

int main() {
    std::ifstream jin("Story.txt");
    if(!jin) {
        std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
        return 1;
    }
 
    char a[100];
    while(true) {
        jin.getline(a, 100);
        std::cout << a; // output what we got

        if(jin) {
            // got a complete line, add a newline to the output
            std::cout << '\n';
        } else {
            // did not get a newline
            if(jin.eof()) break; // oh, the end of the file, break out

            // reset the failbit to continue reading the long line
            jin.clear();
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章