2017-07-28 6 views
-2

私は行から単語を取得するコードを書いています。私はそれに対して直接的な機能を得ることができなかったので、これは私が書いたコードです。私はそれを私のメインプログラムで何度も呼び出す必要があるので、私はそれを機能させました。しかし、メインループの中で呼び出すときはいつでも、変数bは初期化されていません。どんな助けも高く評価されます。 TIA!実行時エラー、変数b未初期化

vector <string> output_words(string stri) //FUNCTION TO GET INDIVIDUAL WORDS FROM A LINE 
{ 
    vector <string> substring; // Contains words from single lines 
    vector <string> output1; 


    int b; 

    //create variables that will act as "cursors". output words between them. 
    size_t pos1 = 0; 
    size_t pos2; 

    string str;// = "Hello My Nme is Ruth"; 




    int a = str.length(); // abc[i] is a string in the vector, NOT THE VECTOR! 

    for (int x = 0; x < a; x++) 
    { 
     pos2 = str.find(" ", pos1); 
     //substring.resize(i); 
     substring.resize(a); // Need to resize a vector so never points to zero 
     substring[x] = str.substr(pos1, (pos2 - pos1)); 
     substring.push_back(substring[x]); 
     //std::cout << "pos1:" << pos1 << ", pos2:" << pos2 << std::endl; 
     pos1 = pos2 + 1; // sets pos1 to the next character after pos2. 
         //so, it can start searching the next " ". 
     if (x > 0) 
     { 
      if (substring[0] == substring[x]) 
      { 
       substring.erase(substring.begin() + x); 
       //one_string.erase(one_string.end()); 
       b = x; 
       goto label; 
      } 
     } 
    } 


label: for (int i = 0; i < b; i++) 
    { 
     output1.resize(b); 
     output1[i] = substring[i]; 

    } 

    return output1; 
} 
+0

文字列が空の場合の処理​​を考えてください。また、私はgotoの代わりに休憩を使用します。 – drescherjm

+0

あなたの質問のほかに、なぜここで 'goto'を使っていますか?それは完全に正当化されていないようだ。 – Carcigenicate

+0

ここで 'goto'は何をしていますか?それが流動制御の核兵器オプションです。 – tadman

答えて

1

変数int b;を設定していないため、文字通り初期化されていません。あなたがしなければならないのは、bに何か(通常は0)を設定するだけです。

0

bの値を更新していません。 6行目に変数bを宣言していますが、初期化されていません。適切な値に初期化してください。

0

あなたはfor { if { if { /* * */ } } }bに割り当てるしようとしているので、(一定の条件が満たされていない場合)それはおそらく、任意の値が割り当てられていません。この場合、label: for (int i = 0; i < b; i++)undefined behaviorにつながる未初期化bにアクセスしようとしています。

関連する問題