问题
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.
回答1:
Your input is:
foo,Hello World,foofoo
Your first line that reads input from std::cin
is:
cin >> stringOne;
That line reads everything until it finds the first whitespace character to stringOne
. After that line, the value of strinOne
will be "foo,Hello"
.
In the lines
getline(str, stringOne, ',');
getline(str, stringTwo, ',');
"foo"
is assigned to stringOne
and "Hello"
is assigned to stringTwo
.
In the line
getline(str, stringThree);
nothing is assigned to stringThree
since there is nothing else left in the str
object.
You can fix the problem by changing the first line that reads from std::cin
so that the entire line is assigned to stringOne
, not the contents up to the first whitespace character.
getline(cin, stringOne);
istringstream str(stringOne);
getline(str, stringOne, ',');
getline(str, stringTwo, ',');
getline(str, stringThree);
来源:https://stackoverflow.com/questions/48980998/cin-with-spaces-and