我正在编写代码以从一行中获取单词。由于我无法获得任何直接功能,这就是我写的代码。我需要在我的主程序中一次又一次地调用它,因此我已经将它作为一个函数。但是,只要我在主循环内部调用它,它就会说变量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