我正在編寫代碼以從一行中獲取單詞。由於我無法獲得任何直接功能,這就是我寫的代碼。我需要在我的主程序中一次又一次地調用它,因此我已經將它作爲一個函數。但是,只要我在主循環內部調用它,它就會說變量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;
}
想想如果字符串爲空會發生什麼。我也會用休息而不是跳轉。 – drescherjm
除了你的問題,你爲什麼在這裏使用'goto'?它的使用似乎完全沒有道理。 – Carcigenicate
goto在這裏做什麼?這是流量控制的核武器選擇。 – tadman