如何在c ++中捕获无效输入?

Joh*_*ith 3 c++ syntax try-catch

我是一个(有点)经验丰富的 Python 程序员,试图迁移到 C++。我希望能够捕获无效的用户输入。例如,如果一个变量需要一个整数,而用户键入一个字符串,我想捕获该错误。在python 3中,语法是:

try:
    #block of code you want to run
except ValueError:
    #Block of code to be run if the user inputs an invalid input
Run Code Online (Sandbox Code Playgroud)

在 C++ 中,我读到语法是 Try、catch。我正在尝试这样做,但它不起作用。这是我在 C++ 中的代码:

#include "Calculator.h"
#include <iostream>
#include <exception>

using namespace std;

Calculator::Calculator()
{
}

int Calculator::Calc()
{
    cout << "Enter a number " << endl;
try
{
    cin >> a;
}
catch (logic_error)
{
    cout << "An error has ocurred! You have entered an invalid input!"
}
Run Code Online (Sandbox Code Playgroud)

如何在 C++ 中捕获无效输入?是的,我正在使用这个类的头文件。如果您需要这些内容,请告诉我。如果我找到了答案,我会继续在网上搜索并发布!

nhg*_*rif 5

你需要 #include <limits>

int x;
std::cout << "Enter a number: ";
std::cin >> x;
while(std::cin.fail()) {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    std::cout << "Bad entry.  Enter a NUMBER: ";
    std::cin >> x;
}
std::cout << "x = " << x << std::endl;
Run Code Online (Sandbox Code Playgroud)

有一个模板给你。

  • @JohnBobSmith 每次导入模块时,`using namespace std` 与`from Foo import *` 一样糟糕。最终你会遇到名称冲突,调用错误的函数等。在任何地方使用 `std::` 通常太麻烦,所以一个很好的平衡是只在函数内部使用 `using namespace std;`,或者`使用 std:: cin; 使用 std::cout` 有选择地将名称引入全局命名空间。 (2认同)