2012-01-07 25 views
0

文字列の区切り文字 "、"をトークン化するコードを書いていました。ベクトル上の配列添字演算子

void Tokenize(const string& str, vector<string>& tokens, const string& delimeters) 
    { 
     // Skip delimiters at beginning. 
     string::size_type lastPos = str.find_first_not_of(delimiters, 0); 
     // Find first "non-delimiter". 
     string::size_type pos  = str.find_first_of(delimiters, lastPos); 

     while (string::npos != pos || string::npos != lastPos) 
     { 
     // Found a token, add it to the vector. 
     tokens.push_back(str.substr(lastPos, pos - lastPos)); 
     // Skip delimiters. Note the "not_of" 
     lastPos = str.find_first_not_of(delimiters, pos); 
     // Find next "non-delimiter" 
     pos = str.find_first_of(delimiters, lastPos); 
     } 
    } 

    int main() 
    { 
     string str; 
     int test_case; 
     cin>>test_case; 
     while(test_case--) 
     { 
      vector<string> tokens; 
      getline(cin, str); 
      Tokenize(str, tokens, ","); 
      // Parsing the input string 
      cout<<tokens[0]<<endl; 
     } 
     return 0; 
    } 

実行中にセグメンテーション違反が発生します。私はそれをデバッグするときのライン

cout<<tokens[0]<<endl 

cplusplus.comで、それはベクトル

+3

プログラムを実行すると、 'tokens'に要素がありますか?そうでなければ、アクセスされるインデックス「0」の要素は存在しない。 –

+0

Vector <>で内部的にまだ作成されていないメモリにアクセスしている可能性があります。これは、あなたがベクトルのインスタンスに何かをプッシュするときに発生します。 – ScarletAmaranth

答えて

1
cin>>test_case; // this leaves a newline in the input buffer 
while(test_case--) 
{ 
    vector<string> tokens; 
    getline(cin, str); // already found newline 
    Tokenize(str, tokens, ","); // passing empty string 

あなたのトークン化機能を見ていなければ、私は意味し、空のベクター、でその空の文字列の結果を推測しますtokens[0]を印刷すると、その要素は実際には存在しません。 getlineに電話する前に入力バッファが空であることを確認する必要があります。たとえば、番号入力の直後にcin.ignore()に電話をかけることができます。

また、operator>>を無視してgetlineだけを使用することもできます。その後、好きな方法で文字列を変換に変換します。

1

の値をaccesingため[] operartorsは、それが可能読むことです使用しているためproblem.Iの原因は理由を理解することはできませんでしたstd::getline()を使用して成功しませんでしたか?この場合、文字列は空になり、添字演算子を使用するとクラッシュします。あなたは、常に例えば、読み取りが読み取ろうと後成功したかどうかをテストする必要があります:

if (std::getline(std::cin, str)) { 
    // process the read string 
} 
関連する問題