【问题标题】:Exception handling to detect input string vs. int检测输入字符串与 int 的异常处理
【发布时间】:2022-11-18 03:56:06
【问题描述】:

给定的程序读取单个单词的名字和年龄(以 -1 结尾)的列表,并输出随着年龄递增的列表。如果一行中的第二个输入是字符串而不是 int,程序将失败并抛出异常。在代码中的FIXME处,添加try/catch语句捕获ios_base::failure,并输出0为age。

例如:如果输入是:

Lee 18
Lua 21
Mary Beth 19
Stu 33
-1

那么输出是:

Lee 19
Lua 22
Mary 0
Stu 34
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;
}

我无法在捕获异常后清除 cin,甚至尝试将变量设置为空字符串...我的程序在 cin >> inputName 处停止;在捕获到异常之后,但我认为 cin.clear(80, '\n');重置 cin 并将其置于可用状态?

当我尝试将另一个字符串输入 inputName 变量时,调试器告诉我存在未处理的异常。感谢您的帮助,谢谢。

【问题讨论】:

  • 你的程序does not compilestd::cin.clear 只接受一个值:要设置的新状态。
  • 输入始终是文本,因此问题是文本是否可以转换为整数。方法是检查转换是否成功:if (std::cin &gt;&gt; age) { /* do something with age */ } else { /* input failed; recover */ }。这是常用的习惯用法,它比尝试处理异常要简单得多。
  • clear 设置流状态标志。它不会删除数据。您需要clear流,然后ignore错误的输入。

标签: c++


【解决方案1】:

我不太明白你要修复什么。无论如何,我只是解决了清洁 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(), '
');
        }
    }

    return 0;
}

如您所见,我没有将任何参数传递给cin.clear(),因为此方法只是在 cin 内的resets the state flags。要清空 cin buffer 而不是您必须使用 cin.ignore() 传递两个参数,第一个是size of the buffer,在这种情况下,我使用数字限制指定它,而第二个参数是告诉它 end character 是什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多