我是一个(有点)经验丰富的 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)
如何在 …