2011-12-15 36 views
0

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

#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");那么它的工作的罚款。我究竟做错了什么?

回答

4

的问题是:

cin>>s; 

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

你想要的是:

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

或者你可以从std::cin

while(std::cin >> j) // Read a number from the standard input. 
+0

是的,他说的。 – littleadv 2011-12-15 07:50:41

0

似乎在第一空白cin>>s站直接读取数字。试试这个:

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