快速提问,
假设您被告知要从一个文本文件中读取只有 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
four
和 twelve
都被忽略了,five
和 six
之间的空行也是如此。这是否是您寻求的是您的决定,但至少您拥有比以前更接近的东西。
关于c++ - 从文件 C++ 中读取 "n"行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23319696/