我的输入文件是:
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
为什么会这样?我该如何修复它,以便即使有额外的空间它也能读取正确的输入? 任何帮助,将不胜感激。谢谢!
最佳答案
问题出在 while (number1.good())
循环中。在number1 >> temp1
提取失败之后 之前,number1
不会设置失败状态,但是直到下次测试循环条件时,即在您打印出该提取的结果之后。您应该将内部循环更改为:
while (number1 >> temp1)
{
std::cout << temp1 << std::endl;
}
这将提取值,然后测试提取是否成功,如果提取失败则跳出循环,这就是您想要的行为。
关于C++:为什么程序从输入文件中读取最后一个空白作为元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3102937/