2017-07-28 72 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

想想如果字符串为空会发生什么。我也会用休息而不是跳转。 – 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++)正试图访问未初始化的b,这将导致undefined behavior