无法从 stringstream 解析数字并正确输出它们 C++
Failing to parse numbers from stringstream and output them correctly C++
#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”? (这是为了让程序只显示那些值,而不是错误引起的大量零)以及为什么会发生此错误?
在此先感谢您的帮助。
问题是您的循环在检测到故障状态后没有 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
,解决您的问题。
#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”? (这是为了让程序只显示那些值,而不是错误引起的大量零)以及为什么会发生此错误?
在此先感谢您的帮助。
问题是您的循环在检测到故障状态后没有 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
,解决您的问题。