0

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);
}
William Miller
  • 8,060
  • 3
  • 13
  • 39
Israel
  • 1
  • 1
  • "But I find that I have to make a enter in cin.ignore", i'm not sure what you mean. – George Nov 12 '17 at 02:11
  • @George Sorry for not a native English user. i mean isn't need to input '\n' in cin.ignore when running command? how to skip this step? – Israel Nov 12 '17 at 02:31
  • 1
    Well, you could obviously always write a function that calls `ignore` and passes `'\n'` as the delimiter to it, but is it really so much bother to just write a comma followed by `'\n'`? – Benjamin Lindley Nov 12 '17 at 03:20
  • @benjamin-lindley no I mean aint I have to enter once in cin.ignore before inputting value in getline? any method to skip this and just inputting value? – Israel Nov 12 '17 at 03:31
  • It seems your issue is mixing formatted and unformatted I/O. There are hundreds of answers on dealing with these. Most likely you shouldn’t use `ignore()` but rather replace it by a use of `std::ws`. Your question doesn’t really state what the actual problem is, i.e., this is to a large extend based on my crystal ball. – Dietmar Kühl Nov 12 '17 at 03:56
  • @Dietmar-Kühl i figure out how to explain my problem now. my question should is it have a way to clear the cin buffer in C++ with discard characters without extracting? – Israel Nov 12 '17 at 04:42

1 Answers1

0

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;".

Zig Razor
  • 2,907
  • 2
  • 8
  • 27