逐行读取txt

Reading txt line by line

本文关键字:txt 读取 逐行      更新时间:2023-10-16

我正在C++中逐行读取一个文本文件。我使用的是这个代码:

while (inFile)
{
getline(inFile,oneLine);
}

这是一个文本文件:

-------
This file is a test to see 
how we can reverse the words
on one line.
Let's see how it works.
Here's a long one with a quote from The Autumn of the Patriarch. Let's see if I can say it all in one breath and if your program can read it all at once:
Another line at the end just to test.
-------

问题是,我只能阅读以"这是一个很长的等等…"开头的段落,而它的结尾是"立刻:"我无法解决阅读所有文本的问题。你有什么建议吗?

正确的换行习惯用法是:

std::ifstream infile("thefile.txt");
for (std::string line; std::getline(infile, line); )
{
    // process "line"
}

或者不喜欢for循环的人的替代方案:

{
    std::string line;
    while (std::getline(infile, line))
    {
        // process "line"
    }
}

请注意,即使无法打开文件,这也能正常工作,尽管如果您想为该情况生成专用诊断,您可能需要在顶部添加一个额外的检查if (infile)