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++ 中捕获无效输入?是的,我正在使用这个类的头文件。如果您需要这些内容,请告诉我。如果我找到了答案,我会继续在网上搜索并发布!
你需要 #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)
有一个模板给你。
| 归档时间: |
|
| 查看次数: |
25051 次 |
| 最近记录: |