我正在编写一个代码来获取一行中的单词。由于我无法获得任何直接功能,这就是我编写的代码。我需要在我的主程序中一次又一次地调用它,因此我已经使它成为一个函数。但是,每当我在主循环中调用它时,它表示变量b未初始化。任何帮助都非常感谢。 TIA!
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 :(得分:1)
您没有将变量int b;
设置为任何内容,它实际上是未初始化的。您所要做的就是将b
设置为某个(通常为0)。
答案 1 :(得分:0)
您尚未更新b的值。你刚刚在第6行声明了变量b而没有初始化。所以请将它初始化为适当的值。
答案 2 :(得分:0)
由于您尝试在b
内分配for { if { if { /* * */ } } }
,因此可能未分配任何值(如果不满足某些条件)。如果发生这种情况,则label: for (int i = 0; i < b; i++)
会尝试访问未初始化的b
,这会导致undefined behavior
。