无法从stringstream中解析数字并正确输出
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"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
,从而解决您的问题。
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 如何将输出数字划分为奇数和偶数
- 输出错误,问题是找到总和5000位数字cpp
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 以C++输出一个数字三角形
- C++输出奇怪的字符而不是数字 (Windows)
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 反向输出数字 - c++
- 为什么当我输入一个大数字时,输出会一遍又一遍地重复?
- 未来值公式显示疯狂巨大数字的输出
- 输出一个数字,该数字可能是三种类型之一
- 预期输出之后的所有这些数字是多少
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 素数检查 C++ 函数输出非素数的数字
- 如何将数字输出到文件中,所有数字都具有相同的精度
- 下面的代码是如何工作的?它输出分解的数字并且功能齐全,我只是不明白它是如何做到的
- C++ 如何从输入字母或数字输出字母或数字
- gcc 预处理的表单哈希符号 + 数字"# 1"输出行是什么意思?
- C++ 意外的数字输出
- 数据将奇怪的数字输出到文件,MAP C++