简体   繁体   中英

why cursor not go to next line? When getline() take "\n" as an input

I was learning from https:\/\/www.learncpp.com\/cpp-tutorial\/an-introduction-to-stdstring\/<\/a> and a question arises from the below code

#include <string>
#include <iostream>

int main()
{
    std::cout << "Pick 1 or 2: ";
    int choice{};
    std::cin >> choice;

    std::cout << "Now enter your name: ";
    std::string name{};
    std::getline(std::cin, name); // note: no std::ws here

    std::cout << "Hello, " << name << ", you picked " << choice << '\n';

    return 0;
}

From the documentation<\/a> for std::getline():

 getline reads characters from an input stream and places them into a string:
 1) Behaves as UnformattedInputFunction, except that input.gcount() is not affected. After constructing and checking the sentry object, performs the following:
    1) Calls str.erase()
    2) Extracts characters from input and appends them to str until one of the following occurs (checked in the order listed)
       a) end-of-file condition on input, in which case, getline sets eofbit.
       b) the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str.
       c) str.max_size() characters have been stored, in which case getline sets failbit and returns.

because there is still a \\n in the input buffer from the first read of choice<\/code> , you need to tell cin to ignore it.

int choice{};
std::cin >> choice;
std::cin.ignore(); <<<=============
std::cout << "Now enter your name: ";
std::string name{};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM