Cin With Space和“," [英] Cin With Spaces and ","
问题描述
我试图弄清楚如何将用户输入的string
与空格作为单个string
一起使用.而且,此后,用户将包括其他用逗号分隔的strings
.
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.
例如,foo,Hello World,foofoo
,其中foo
是一个string
,后跟Hello World
和foofoo
.
For example, foo,Hello World,foofoo
where foo
is one string
followed by Hello World
and foofoo
.
我现在拥有的东西,它将把Hello World
分成两个strings
而不是将它们组合成一个.
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;
}
如何将Hello World
作为单个字符串而不是两个字符串输入到stringTwo
中.
How do I get Hello World
into stringTwo
as a single string instead of two.
推荐答案
您的输入是:
foo,Hello World,foofoo
从std::cin
读取输入的第一行是:
Your first line that reads input from std::cin
is:
cin >> stringOne;
该行将读取所有内容,直到找到stringOne
的第一个空格字符为止.在该行之后,strinOne
的值将为"foo,Hello"
.
That line reads everything until it finds the first whitespace character to stringOne
. After that line, the value of strinOne
will be "foo,Hello"
.
在线
getline(str, stringOne, ',');
getline(str, stringTwo, ',');
将
"foo"
分配给stringOne
,将"Hello"
分配给stringTwo
.
"foo"
is assigned to stringOne
and "Hello"
is assigned to stringTwo
.
在线
getline(str, stringThree);
没有任何内容分配给stringThree
,因为str
对象中没有其他内容.
nothing is assigned to stringThree
since there is nothing else left in the str
object.
您可以通过更改从std::cin
读取的第一行来解决此问题,以便将整个行分配给stringOne
,而不是将内容分配给第一个空格字符.
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);
这篇关于Cin With Space和“,"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!