想要使用流解析int的字符串输入

时间:2011-12-15 07:44:04

标签: c++ stringstream

我是c ++编程的新手。我已经阅读了如何使用向量(Int tokenizer)在SO问题中完成解析。但我已经尝试了以下数组。我只能从字符串中解析一个数字。如果输入字符串是“11 22 33 etc”。

#include<iostream>
#include<iterator>
#include<vector>
#include<sstream>

using namespace std;

int main()
{

int i=0;
string s;
cout<<"enter the string of numbers \n";
cin>>s;
stringstream ss(s);
int j;
int a[10];
while(ss>>j)
{

    a[i]=j;
    i++;
}
for(int k=0;k<10;k++)
{
    cout<<"\t"<<a[k]<<endl;
}

}

如果我输入“11 22 33”

output

11
and some garbage values.

如果我已初始化stringstream ss("11 22 33");,那么它的工作正常。我做错了什么?

3 个答案:

答案 0 :(得分:4)

问题在于:

cin>>s;

将一个空格分隔的单词读入s。所以只有11个进入s。

你想要的是:

std::getline(std::cin, s);

或者,您可以直接从std::cin

读取数字
while(std::cin >> j) // Read a number from the standard input.

答案 1 :(得分:0)

似乎cin>>s停在第一个空白处。试试这个:

cout << "enter the string of numbers" << endl;
int j = -1;
vector<int> a;
while (cin>>j) a.push_back(j);

答案 2 :(得分:0)

We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type variables

cin >> mystring;

However, as it has been said, cin extraction stops reading as soon as if finds any blank space character, so in this case we will be able to get just one word for each extraction.

来自http://www.cplusplus.com/doc/tutorial/basic_io/

所以你必须使用getline()

string s;
cout<<"enter the string of numbers \n";
getline(cin, s);