I’ve been trying to split up an input string into smaller strings delineated by whitespace. I found this code from here:
stringstream ss ("bla bla");
string s;
while (getline(ss, s, ' ')) {
cout << s << endl;
}
which works just fine. However, if I replace “bla bla” with a variable containing a string:
string userInput;
cin >> userInput;
stringstream ss (userInput);
string s;
while (getline(ss, s, ' ')) {
cout << s << endl;
}
only the first word/char/string prints out. Why is that? Is there a way to fix it? I’ve looked around at some stringstream questions, but the problem is that I don’t really know what I’m looking for.
Your problem isn’t
stringstream ss (userInput);, it’s the behavior ofstd::cin. Any whitespace will end the extraction of formatted user input, so the inputbla blawill result in onestd::string s = "bla"and another string"bla"waiting for extraction.UseIf you want to get a line, usecin >> noskipws >> userInput;instead.std::getline(std::cin,userInput)instead. Have a look at this little demonstration, which comparesstd::getlinetostd::cin::operator>>on your inputbla bla:Source:
Result:
See also:
std::getlinefrom<string>(alternative resource).(This will only prevent skipping leading whitespaces, a whitespace will still terminate the extraction).noskipwsistream::operator>>