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

c++-如何正确处理ios :: failbit

(c++ - How to handle the ios::failbit correctly)

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

我想制作一个接受输入直到输入-1并使用异常正确处理输入的程序。

它接受用户输入FirstNameAge然后将FirstName年龄和增加的年龄打印1。如果第二个变量不是整数(年龄),则应该打印FristName0

但是我的程序给了我意外的输出。我怎样才能解决这个问题?

提前致谢。

输入格式

John 12

Michel 15

Alice Graz 11

Bob 15

-1

预期产量

John 13

Michel 16

Alice 0

Bob 16

我的密码

#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

尝试cin.ignore()像这样使用

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

你必须包括<limits>头文件。