getline(cin, aString) receiving input without another enter

后端 未结 3 1941
我在风中等你
我在风中等你 2021-01-12 15:31

My code looks like this,

string aString;
cin >> aString;
cout << \"This is what cin gets:\" << aString << endl;
getline(cin, aString)         


        
3条回答
  •  情歌与酒
    2021-01-12 16:15

    this is what I get:

    std::string str;
    std::cin >> str;  //hello world
    std::cout << str;  //hello
    

    this is because the stream operator tokenizes on white space

    std::string str;
    std::getline(std::cin, str);  //hello world
    std::cout << str;  //hello world
    

    you get the full line, getline() works until it find the first end of line and returns that value as a string.

    However when tokenizing, if there are characters (for example a '\n') left in the stream then these will be accessed when getline is called, you will need to clear the stream.

    std::cin.ignore();
    

提交回复
热议问题