Reputation: 13
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.
Upvotes: 1
Views: 3347
Reputation: 105955
Your problem isn't stringstream ss (userInput);
, it's the behavior of std::cin
. Any whitespace will end the extraction of formatted user input, so the input bla bla
will result in one std::string s = "bla"
and another string "bla"
waiting for extraction.
Use If you want to get a line, use cin >> noskipws >> userInput;
instead.std::getline(std::cin,userInput)
instead. Have a look at this little demonstration, which compares std::getline
to std::cin::operator>>
on your input bla bla
:
Source:
#include <iostream>
#include <string>
int main(){
std::string userInput;
std::cout << "Using std::getline(std::cin,userInput) on input \"bla bla\"." << std::endl;
std::getline(std::cin,userInput);
std::cout << "userInput contains \"" << userInput << "\"" << std::endl;
std::cout << "std::cin >> userInput on input \"bla bla\"." << std::endl;
std::cin >> userInput;
std::cout << "userInput contains \"" << userInput << "\"" << std::endl;
return 0;
}
Result:
Using std::getline(std::cin,userInput) on input "bla bla". userInput contains "bla bla" std::cin >> userInput on input "bla bla". userInput contains "bla"
See also:
std::getline
from <string>
(alternative resource).noskipws
istream::operator>>
Upvotes: 8
Reputation: 10828
This does what you said:
#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
std::string test("bla bla");
std::stringstream stream(test);
std::string temp;
while (getline(stream, temp, ' ')) {
std::cout << temp << std::endl;
}
return 0;
}
It is even what you said you did. But since it works - where is the difference to your code?
And for those who do not have a Microsoft Visual C++ compiler handy and do not understand the differences, here's a code snippet:
std::string test("bla bla");
std::stringstream stream(test);
std::string temp;
while (getline(stream, temp, ' ')) {
std::cout << temp << std::endl;
}
the includes required by that snippet are: <string>
, <sstream>
& <iostream>
. Please insert it into the required method.
Upvotes: 0