简体   繁体   中英

How to skip 'enter' in cin.ignore()

I write a code to check char 'exit' in int cin. But I find that I need to set delimiters in cin.ignore such as '\\n' and input it when running command and I think that is not friendly.

How can I change the code to skip the extracting step , maybe using other code instead of cin.ignore ?

Sorry for everyone who try to read my English and answer as I not a native English user. I mean cin.ignore is to extracts and discards characters until the given character is found, is it have a way to clear the cin buffer in C++ with discarding characters without extracting?

void checkcin(int &y)
{
    string input = "", ans;

    cin.clear();
    cin.ignore(INT_MAX, '\n');
    getline(cin, input);

    while (input == "exit")
    {
        cout << "Are you sure to exit: ";
        cin >> ans;
        if (ans == "yes")
        {
            cout << "Bye." << endl;
            exit(0);
        }
        else if (ans == "no")
        {
            cout << "Then welcome back!";

            cout << "Input again: ";
            cin >> input;
        }
    }
    y = std::stoi(input);
}

The first parameter in the "std::cin.ignore()" that you are using just comes down to a very large number. This should be the maximum number of characters that the input buffer can hold. This number may be different on different systems or even header files for different compilers.

You need to press enter twice because there is nothing in the buffer to ignore. It is waiting for something to be entered to ignore. some people will use this to pause the program before the "return 0;".

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