gpt4 book ai didi

c++ - 逐行读取txt

转载 作者:太空狗 更新时间:2023-10-29 20:29:48 30 4
gpt4 key购买 nike

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

问题是我只能阅读以“Here's a long etc...”开头的段落并“立即停止:”我无法解决阅读所有文本。你有什么建议吗?

最佳答案

正确的台词读法是:

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++ - 逐行读取txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8967083/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com