c++ - 从文件 C++ 中读取 "n"行数

标签 c++

快速提问,

假设您被告知要从一个文本文件中读取只有 10 行的输入;尽管如此,文本文件有 40 行。执行以下操作会不会是糟糕的编程:

while ( infile >> input && num_lines < 10 ) {
      do whatever...
      num_lines++;
}
// closed file
infile.close();

有更好的方法吗?

我应该提到,当我说“行”时,我只是指以下内容:

planet
tomorrow
car
etc

所以是的,要读取一行文本,应该实现 get line 函数

最佳答案

这不会是糟糕的编程。你正在检查你的输入成功比大多数新手要好,所以不要为此感到难过。但是,您当前的循环是不正确的。

错误的地方:

  • 它读取字符串,而不是
  • 它实际上可以读取11 行,处理前十行并丢弃最后一行。

试试这个:

int num_lines = 0;
std::string input;

for (; num_lines < 10 && std::getline(input); ++num_lines)
{
    // do-whatever
}

// num_lines holds the number of lines actually read

编辑:问题更改后更新。

你的输入文件是单词。如果您想确保每行只收到一个单词,并且它们必须以行分隔,则涉及更多工作:

#include <iostream>
#include <sstream>

int num_lines = 0;
std::string input;

while (num_lines < 10 && std::getline(input))
{
    std::istringstream iss(input);
    std::string word;
    if (iss >> word)
    {
        // do-whatever with your single word.

        // we got a word, so this counts as a valid line.
        ++num_lines;
    }
}

这将跳过空白行,只处理每行开头的单个单词。它可以进一步增强以确保单词 read 是行中除了空格和换行符或 EOF 之外的唯一内容,但我严重怀疑您是否需要那么严格的错误检查(甚至 this 紧)。

示例输入

one
two
three four
five

six
seven
eight
nine
ten
eleven twelve

处理过的词

one
two
three
five
six
seven
eight
nine
ten
eleven

fourtwelve 都被忽略了,fivesix 之间的空行也是如此。这是否是您寻求的是您的决定,但至少您拥有比以前更接近的东西。

关于c++ - 从文件 C++ 中读取 "n"行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23319696/

相关文章:

c++ - DXGI API : AcquireNextFrame() never grabs an updated image, 总是空白

c++ - 修复我自己的双向链表中的内存泄漏

c++ - 帮助学习 3d 相机类(class)

c++ - 使用 strcat 后删除字符数组会导致段错误

c++ - MultiMap 读入数据有问题?

c++ - 代码在带有警告的 g​​++ 上编译,但在 clang3.1(Xcode 4.3.3) 上给出相同代码的错误

c++ - OpenGL:调整 LOD 角度?

c++ - 为什么在适用时不隐含 constexpr?

c++ - 在 C++ 中使用 system() 时,我的程序卡住了,我该如何让它继续?

c++ - 带有指针数组的 HDF5 结构