C++:为什么程序从输入文件中读取最后一个空白作为元素
我的输入文件是:
2 5 <-- extra space at the end
4 <--extra space at the end
int main(){
ifstream input("input.txt");
istream& in = input;
string line1;
while( getline(in,line1)){
istringstream number1(line1);
while(number1.good()){
number1 >> temp1;
cout<<temp1<<endl;
}
}
input.close();
}
The problem is with the extra space at the end of the line my output is:
2
5
5
4
4
which is not what i want.. but if i remove the extra space it would work:
2
5
4
为什么会发生这种情况?我该如何修复它,以便即使有额外的空格,它也能读取正确的输入? 任何帮助将不胜感激。谢谢!
My input file is:
2 5 <-- extra space at the end
4 <--extra space at the end
int main(){
ifstream input("input.txt");
istream& in = input;
string line1;
while( getline(in,line1)){
istringstream number1(line1);
while(number1.good()){
number1 >> temp1;
cout<<temp1<<endl;
}
}
input.close();
}
The problem is with the extra space at the end of the line my output is:
2
5
5
4
4
which is not what i want.. but if i remove the extra space it would work:
2
5
4
why is this happening? and how can i fix it so that even with extra spaces it reads the correct input?
Any help would be appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题出在
while (number1.good())
循环上。number1
失败状态只有在number1 >>之后才会被设置。 temp1
提取失败,但直到下次测试循环条件(即打印出该提取的结果之后)才测试失败状态。您应该将内部循环更改为:这将提取值,然后测试提取是否成功,如果提取失败则退出循环,这是您想要的行为。
The problem is with the
while (number1.good())
loop. Thenumber1
fail state will not be set until after thenumber1 >> temp1
extraction fails, but you don't test the fail state until the next time the loop condition is tested, which is after you print out the result of that extraction. You should change the inner loop to:This will extract the value, then test whether the extraction succeeded and will break out of the loop if the extraction fails, which is the behavior you want.
尝试将其更改
为
:并查看是否效果更好。问题不在于它读取最后一个空白作为元素,而是
stream.good()
一直保持 true,直到之后读取失败,因此您正在执行循环一次太频繁。或者,将整个内容替换为如下内容:
Try changing this:
To:
and see if it doesn't work better. The problem isn't that it's reading the last blank as an element, but that
stream.good()
remains true until after a read that fails, so you're executing the loop once too often.Alternatively, replace the whole thing with something like this:
有两件事:
恕我直言,您在这里滥用流。不需要第二个流。您可以简单地:
其次,我认为问题出在您的 number1.good() 调用上。这并不能保证所有坏流位。最好像我上面那样使用提取语句本身来检查提取。
Two things:
You're abusing streams here IMHO. There is no need for a second stream. You can simply:
Secondly, I think the problem is your number1.good() call. this does not guarantee all bad stream bits. It's best to check extraction using the extraction statement itself like I did above.