Problems with strings
-
Hello, I recently started to learn C++ and I am here because I wasn't able to find much help online.
My Problem is that most of the time I work with strings, I get "out_of_range" errors. This happens most of the time when I work with one string, e.g. search specific chars,
and then write this new string into another one. But the length of that second string is unknown from the beginning, so all I can think of is to declare an empty string with
spaces (string s=" (insert as much spaces until u cant get out of range "; )
I hope I could somehow make my problem clear, I added one small example to help me express my problem a little bit further. It is a function that splits a string in two parts after the searched char.void func(char zeichen, string eingabe, string erster_teil, string zweiter_teil) { bool firstc = true; erster_teil = " "; zweiter_teil = " "; int counter = 0; for (int i = 0; i < eingabe.size(); i++) { if (eingabe.at(i) != zeichen && firstc) { erster_teil.at(i) = eingabe.at(i); } else if (eingabe.at(i) == zeichen && firstc == true) { firstc = false; } else { zweiter_teil.at(counter) = eingabe.at(i); counter++; } } }
-
Wenn ich dein Problem richtig verstanden habe, versucht du Zeichen im eingegeben String zu finden und in einen Zweiten zu schreiben.
Dafür gibt es die funktionen
std::string::find(char c)
und
std::string::pus_back(char c)Beide zu finden in der Dokumentation zu std::string
http://www.cplusplus.com/reference/string/string/Bsp:
std::string a = "test"; std::string b; int pos = a.find('t'); if(pos != std::string::npos) b.push_back(a.at(pos)); //b enthält dann das das "t"
Code nicht getestet, müsste aber funktionieren
-
Englische Frage und deutscher Code
Schau dir mal die Methoden an, die std::string noch so bietet: http://www.cplusplus.com/reference/string/string/?kw=string
Du kannst auch Zeichen an den (leeren) String anhängen.