Cin 带空格和 ","
Posted
技术标签:
【中文标题】Cin 带空格和 ","【英文标题】:Cin With Spaces and "," 【发布时间】:2018-02-26 03:23:53 【问题描述】:我试图弄清楚如何将用户输入的string
与空格作为单个string
。此外,在此之后,用户将包含其他strings
,以逗号分隔。
例如,foo,Hello World,foofoo
,其中foo
是一个string
,后跟Hello World
和foofoo
。
我现在拥有的是将Hello World
拆分为两个strings
,而不是将它们合并为一个。
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 tokenize a string in C++?的可能重复 您有什么问题要问我们吗? @RSahu 抱歉,我的问题是如何将Hello World
作为单个字符串而不是两个字符串转换为 stringTwo
。
逗号分隔的数据在How can I read and parse CSV files in C++?中处理
使用std::getline()
而不是operator>>
来读取用户的输入:getline(cin, stringOne);
【参考方案1】:
您的输入是:
foo,Hello World,foofoo
从std::cin
读取输入的第一行是:
cin >> stringOne;
该行读取所有内容,直到找到stringOne
的第一个空白字符。在该行之后,strinOne
的值将是 "foo,Hello"
。
在行中
getline(str, stringOne, ',');
getline(str, stringTwo, ',');
"foo"
分配给stringOne
,"Hello"
分配给stringTwo
。
排队
getline(str, stringThree);
没有分配给stringThree
,因为str
对象中没有任何其他内容。
您可以通过更改从std::cin
读取的第一行来解决此问题,以便将整行分配给stringOne
,而不是第一个空格字符之前的内容。
getline(cin, stringOne);
istringstream str(stringOne);
getline(str, stringOne, ',');
getline(str, stringTwo, ',');
getline(str, stringThree);
【讨论】:
啊..好的,我现在明白了。谢谢你的帮助!。以上是关于Cin 带空格和 ","的主要内容,如果未能解决你的问题,请参考以下文章
为啥 isNaN(" ")(带空格的字符串)等于 false?