2009-07-17 6 views
0

ユーザから数字のリストを取得してトークン化するには?stdinから数字のリストを取得してトークン化する

これは私が持っているものですが、それは最初の数以外の何かを取得していません:

#include <iostream> 
#include <sstream> 
#include <vector> 
#include <string> 

using namespace std; 

int main() 
{ 

    string line = ""; 
    cin >> line; 

    stringstream lineStream(line); 

    int i; 
    vector<int> values; 

    while (lineStream >> i) 
     values.push_back(i); 

    for(int i=0; i<values.size(); i++) 
     cout << values[i] << endl; 

    system("PAUSE"); 
    return 0; 
} 

関連記事:
C++, Going from string to stringstream to vector
Int Tokenizer

+0

1行に複数の数字をスペースで区切って入力すると、すべての数字が入力されます。問題は、最初の行だけを読んでいることです。 –

答えて

4

私は空白のCIN >>ブレークを信じますこれは、入力した最初の数字のみを取得していることを意味します。

は、try:

getline(cin, line); 
+1

ループに入れていない場合:while(std :: cin >> i){/ * Do STUFF * /} –

+0

なぜループすればいいですか? –

1

ドニーは空白にCIN区切りを述べたので、私たちは ')(getlineは' を使用することができ、これを克服しないと同じようには、次の例ではうまく動作します:

#include <iostream> 
#include <sstream> 
#include <vector> 
#include <string> 

using namespace std; 

int main() 
{ 

    string line = ""; 
    ::getline(std::cin,line,'\n'); 

    std::stringstream lineStream(line); 

    int i; 
    std::vector<int> values; 

    while (lineStream >> i) 
     values.push_back(i); 

    for(int i=0; i<values.size(); i++) 
     cout << values[i] << endl; 

    system("PAUSE"); 
    return 0; 
} 
0

トップにメインの

string line = ""; 
getline (cin, line); 
stringstream lineStream(line); 
5

cinから値を読み取るには、おそらく最も簡単な方法ですontainer:

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

int main() 
{ 
    std::vector<int> values; 
    std::copy(
     std::istream_iterator<int>(std::cin), 
     std::istream_iterator<int>(), 
     std::back_inserter(values)); 

    // For symmetry with the question copy back to std::cout 
    std::copy(
     values.begin(), 
     values.end(), 
     std::ostream_iterator<int>(std::cout,"\n")); 

} 
0

これは、getlineの文字列バージョンであり、istreamの文字列バージョンではありません。

0

OK:パベル・ミナエフが最高の答えを持っています。
しかし、そのことに言及しているすべての人が空白に壊れています。
これは良いことです(空白も無視されるため)。

#include <iostream> 
#include <sstream> 
#include <vector> 
#include <string> 

using namespace std; 

int main() 
{ 

    int i; 
    vector<int> values; 

    // prefer to use std::copy() but this works. 
    while (std::cin >> i) 
    { 
     values.push_back(i); 
    } 

    // prefer to use std::copy but this works. 
    for(vector<int>::const_iterator loop = values.begin();loop != values.end();++loop) 
    { 
     cout << *loop << endl; 
    } 

    return 0; 
} 
関連する問題