我试图弄清楚如何采取用户进入空间的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
。
你的意见是:
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);