Cin With Spaces和“,”

问题描述 投票:0回答:1

我试图弄清楚如何采取用户进入空间的string作为单个string。此外,在此之后,用户将包括以逗号分隔的其他strings

例如,foo,Hello World,foofoo,其中foo是一个string,其次是Hello Worldfoofoo

我现在所拥有的,它会将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

c++ string getline
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.