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