Warm tip: This article is reproduced from serverfault.com, please click

How to handle the ios::failbit correctly

发布于 2020-12-02 14:52:22

I tried to make a program that takes the inputs until the -1 is entered and handles the inputs properly using exceptions.

It takes user inputs FirstName and Age and print the FirstName and increased age by 1. If the second variable is not an integer(age) then it should print FristName and 0.

But my program gives me an unexpected output. How can I fix this?

Thanks in advance.

Input format

John 12

Michel 15

Alice Graz 11

Bob 15

-1

Expected Output

John 13

Michel 16

Alice 0

Bob 16

My code

#include <string>
#include <stdexcept>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    string inputName;
    int age;

    cin.exceptions(ios::failbit);

    cin >> inputName;
    while (inputName != "-1")
    {
        try
        {
            cin >> age;
        }
        catch (exception ex)
        {
            age = -1;
            if (cin.fail())
                cin.clear();
            cin.ignore();
        }

        cout << inputName << " " << (age + 1) << endl;

        cin >> inputName;
    }

    return 0;
}
Questioner
Jacobe
Viewed
0
Harry 2020-12-02 23:20:15

try using cin.ignore() like this

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

You have to include <limits> header file.