C++:为什么程序从输入文件中读取最后一个空白作为元素

标签 c++ input whitespace

我的输入文件是:

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/

相关文章:

c++ - 当使用 "%x"打印 numeric_limits<float>::infinity() 时会发生什么?

c++ - 外部结构前向声明

c++ - 如何使用 C 或 C++ 获取目录中的文件列表?

c - 如何测试具有多个输入的 C 程序?

java - 如何分配从 .txt 文件读取的值?

C++:引用作为构造函数参数,帮助

java - 如何在计算中使用用户输入的字符?

Bash 脚本自动创建符号链接(symbolic link)到树中的子目录

java - 检测空白字符串

java - Java String split() 的意外行为