Home > Mobile >  How to clear cin input buffer
How to clear cin input buffer

Time:11-18

int main() {
    string inputName;
    int age;
    // Set exception mask for cin stream
    cin.exceptions(ios::failbit);

    cin >> inputName;
    while (inputName != "-1") {
        // FIXME: The following line will throw an ios_base::failure.
        //        Insert a try/catch statement to catch the exception.
        //        Clear cin's failbit to put cin in a useable state.

        try
        {
            cin >> age;
            cout << inputName << " " << (age   1) << endl;
        }

        catch (ios_base::failure& excpt)
        {
            age = 0;
            cout << inputName << " " << age << endl;
            cin.clear(80, '\n');

        }

        inputName = "";

        cin >> inputName;

    }

    return 0;
}

I'm unable to clear cin after catching the exception, even trying to set the variable to an empty string... my program stops at cin >> inputName; after the exception is caught but I thought cin.clear(80, '\n'); resets cin and puts it in a usable state?

Debugger is telling me that there is an unhandled exception when I try to input another string into inputName variable. Any help is appreciated, thank you.

CodePudding user response:

I don't quite understand what you want to fix. In any case, I just fixed the problem with cleaning the cin.

#include <iostream>
#include <limits>

using namespace std;

int main() {
    string inputName;
    int age;
    
    // Set exception mask for cin stream
    cin.exceptions(ios::failbit);
    
    cout << "Input name: ";
    cin >> inputName;
    while (inputName != "-1") {
        // FIXME: The following line will throw an ios_base::failure.
        //        Insert a try/catch statement to catch the exception.
        //        Clear cin's failbit to put cin in a useable state.
        try {
            cout << "Age: ";
            cin >> age;
            cout << inputName << " " << (age   1) << endl;
            break;
        }
        catch (ios_base::failure& except) {
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    return 0;
}

As you can see, I don't pass any parameters to cin.clear() as this method simply resets the state flags inside the cin. To empty the cin buffer instead you have to use cin.ignore() passing two parameters, the first is the size of the buffer, in this case, I used numeric_limits to specify it, while the second parameter is to tell it what the end character is.

  •  Tags:  
  • c
  • Related