【问题标题】:Failing to parse numbers from stringstream and output them correctly C++无法从字符串流中解析数字并正确输出它们 C++
【发布时间】:2015-08-30 14:43:39
【问题描述】:
#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”和“5678”并输出这些值。我将值放在一个整数向量中,稍后我从向量中输出这些值,但是,输出是在前几行中,它向我显示了值,但是随后,我得到了很多零,我从未见过这样的错误,看起来很有趣,所以我的问题是:为什么我没有得到想要的输出值“1234”和“5678”? (这是为了让程序只显示那些值,而不是由错误引起的巨大的零数组)以及为什么会发生这个错误?

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

提前感谢您的帮助。

【问题讨论】:

  • 只要numvec 不为空,for 循环中的条件始终为真。你的意思很可能是i &lt; numvec.size()
  • 谢谢,没注意到。

标签: c++ string parsing int stringstream


【解决方案1】:

问题是您的循环在检测到故障状态后没有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,从而解决您的问题。

Fixed demo.

【讨论】:

  • 谢谢,帮助。但是使用“继续”安全吗?
  • @zLeon 是的,这绝对安全,因为循环的每次迭代都会在读取流中取得一些进展。这意味着您不会陷入无限循环,这是使用continue 的主要危险。
猜你喜欢
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 2017-04-08
相关资源
最近更新 更多