执行命令:
./program < input.txt
使用以下代码检查:
string input;
while(cin) {
getline(cin, input);
}
上面的代码似乎getline()
在输入为空的情况下生成了一个额外的调用。\n
无论input.txt 的最后一行是否有 a,都会发生这种情况。
@Jacob 有正确的解决方案,但由于某种原因删除了他的答案。这是您的循环中发生的事情:
cin
检查任何故障位(BADBIT、FAILBIT)cin
报告没有问题,因为尚未从文件中读取任何内容。getline
调用它检测文件结束,设置 EOF 位和 FAILBIT。你需要做这样的事情:
std::string input;
while(std::getline(std::cin, input))
{
//Have your way with the input.
}
这个怎么样:
string input;
while(getline(cin, input)) {
//do something with input...
}
编辑:请注意,在下面的示例中,我将向您展示“如何检测 EOF”。正如@Billy 指出的那样,您可能希望使用good()
而不是eof()
检测任何错误条件或eof。我在答案的末尾包含了有关此的信息,但这很重要,因此我在顶部添加了此注释以确保其清晰。
(原答案如下)
你要这个:
string input;
while( !cin.eof() ) {
getline(cin, input);
}
使用operator!
on an iostream
only 检查是否发生了故障或其他错误情况。 ios::operator!()。
您可以使用good()
代替!eof()
检查任何条件eof
、badbit
或failbit
。 ios::good()。