逐行读取文本文件

5

我正在使用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.
-------

问题在于我只能阅读以“这是一个很长的等等......”开头的段落,它会在“立即停止”处停止: 我无法解决阅读所有文本的问题。你有什么建议吗?


你知道每次读取一行时都会覆盖oneLine的内容,所以在while循环结束后,oneLine中唯一存在的内容是最后一行的内容。 - PeterT
你并没有真正包含太多的代码... - DilithiumMatrix
1个回答

7
正确的读取行的习惯用语是:
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)

我真希望这个内容能够出现在地球上每一本C++初学者书籍的第一页。 - André Caron
1
@AndréCaron:如果这能让你感到安慰,这是我“经常复制的答案”文件中的第一个条目。 - Kerrek SB
哈哈哈哈,“常贴的答案”!我会记住这个! - André Caron
@KerrekSB:这使它成为一个很好的候选项,可以投票关闭为完全重复。不幸的是,似乎没有一个规范的SO问题包含这个规范的SO答案。 - Ken Bloom
@KenBloom:这种问题可能已经有上千个了...实际上,SO应该有一种机制来创建或标记现有的问题为规范问题,但事实上,大多数问题都相当晦涩,而答案总是相同的... - Kerrek SB
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接