无法从stringstream中解析数字并正确输出

Failing to parse numbers from stringstream and output them correctly C++

本文关键字:数字 输出 stringstream      更新时间:2023-10-16
#include <iostream>        
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main(){
string a = " test 1234 test 5678";
stringstream strstr(a);
string test;
vector<int>numvec;
int num;
while(strstr>>num || !strstr.eof()){
    if(strstr.fail()){
        strstr.clear();
        string kpz;
        strstr>>kpz;
    }
    numvec.push_back(num);
}
for(int i = 0;numvec.size();++i){
    cout<<numvec[i]<<'t';
}
}

在这个程序中,我试图从一个字符串流中解析值"1234"answers"5678",其中包含字符串单词并输出这些值。我把值放在一个整数向量内,后来我从向量输出这些值,然而,输出是,在前几行,它显示了我的值,但是,我得到了很多零,我从来没有见过这样的错误,它看起来很有趣,所以我的问题是:为什么我没有得到值"1234"answers"5678"输出想要的?(这是为了让程序只显示这些值,而不是由错误引起的巨大的零数组)为什么会发生这个错误?

程序:http://ideone.com/zn5j08

提前感谢您的帮助。

问题是,在检测到故障状态后,您的循环没有continue,这意味着即使在故障后,num的值也会被推入numvec

修复方法如下:

while(strstr>>num || !strstr.eof()) {
    if(strstr.fail()){
        strstr.clear();
        string kpz;
        strstr>>kpz;
        continue; // <<== Add this
    }
    numvec.push_back(num);
}

现在,只有当strstr没有处于失败状态时,该值才会被推入numvec,从而解决您的问题。

固定演示。