【发布时间】: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”? (这是为了让程序只显示那些值,而不是由错误引起的巨大的零数组)以及为什么会发生这个错误?
提前感谢您的帮助。
【问题讨论】:
-
只要
numvec不为空,for循环中的条件始终为真。你的意思很可能是i < numvec.size() -
谢谢,没注意到。
标签: c++ string parsing int stringstream