Ich schreibe einen Code, um Wörter aus einer Zeile zu erhalten. Da ich dafür keine direkte Funktion bekommen konnte, ist dies der Code, den ich geschrieben habe. Ich muss es immer wieder in meinem Hauptprogramm nennen, daher habe ich es zur Funktion gemacht. Wenn ich es jedoch innerhalb der Hauptschleife anrufe, heißt es, dass die Variable b nicht initialisiert ist. Jede Hilfe wird sehr geschätzt. TIA!Laufzeitfehler, Variable b nicht initialisiert
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;
}
Denken Sie darüber nach, was passiert, wenn die Zeichenfolge leer ist. Auch würde ich eine Pause anstelle des Goto verwenden. – drescherjm
Neben Ihrer Frage, aber warum benutzen Sie 'goto' hier? Der Gebrauch scheint völlig ungerechtfertigt. – Carcigenicate
Was macht 'goto' hier? Das ist die Kernwaffenoption der Flusskontrolle. – tadman