逐行阅读文本

时间:2012-01-23 04:06:29

标签: c++ file ifstream

我在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.
-------

问题是我只能阅读段落以“这是一个很长的等等......”并且它“立即停止”: 我无法解读所有文字。你有什么建议吗?

1 个答案:

答案 0 :(得分:6)

正确的读线习语是:

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)