I am trying to figure out how to take a string
that a user enters with space as a single string
. Moreover, after that, the user will include other strings
separated by commas.
For example, foo,Hello World,foofoo
where foo
is one string
followed by Hello World
and foofoo
.
What I have right now, it would split Hello World
into two strings
instead of combining them into one.
int main()
{
string stringOne, stringTwo, stringThree;
cout << "Enter a string with commas and a space";
cin >> stringOne; //User would enter in, for this example foo,Hello World,foofoo
istringstream str(stringOne);
getline(str, stringOne, ',');
getline(str, stringTwo, ',');
getline(str, stringThree);
cout << stringOne; //foo
cout << endl;
cout << stringTwo; //Hello World <---should be like this, but I am only getting Hello here
cout << endl;
cout << stringThree; //foofoo
cout << endl;
}
How do I get Hello World
into stringTwo
as a single string instead of two.
Your input is:
Your first line that reads input from
std::cin
is:That line reads everything until it finds the first whitespace character to
stringOne
. After that line, the value ofstrinOne
will be"foo,Hello"
.In the lines
"foo"
is assigned tostringOne
and"Hello"
is assigned tostringTwo
.In the line
nothing is assigned to
stringThree
since there is nothing else left in thestr
object.You can fix the problem by changing the first line that reads from
std::cin
so that the entire line is assigned tostringOne
, not the contents up to the first whitespace character.