逐行读取txt

发布于 2024-12-28 15:41:02 字数 529 浏览 2 评论 0原文

我正在用 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...”开头的段落,并且它“立即停止:” 我无法阅读所有文字。您有什么建议吗?

I am reading a text file line by line in C++. I'm using this code:

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

This is a text file:

-------

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

The problem is I can read only the paragraph starts with "Here's a long etc..." and it stops "at once:"
I couldn't solve to read all text. Do you have any suggestion?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

允世 2025-01-04 15:41:02

正确的行读取习惯用法是:

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)

The correct line reading idiom is:

std::ifstream infile("thefile.txt");

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

Or the alternative for people who don't like for loops:

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

Note that this works as expected even if the file couldn't be opened, though you might want to add an additional check if (infile) at the top if you want to produce a dedicated diagnostic for that condition.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文