2011-12-15 57 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);