如何在c ++中捕获无效的输入? [英] How to catch invalid input in c++?
问题描述
我是一个(有点)经验丰富的python程序员试图迁移到C ++。我想要能够捕获无效的用户输入。例如,如果一个变量需要一个整数,并且用户键入一个字符串,我想捕获该错误。在python 3中,语法是:
I am a (somewhat) experienced python programmer trying to migrate to C++. I want to be able to catch invalid user input. For instance, if a variable requires an integer, and the user types a string, I want to catch that error. In python 3, the syntax is:
try:
#block of code you want to run
except ValueError:
#Block of code to be run if the user inputs an invalid input
在c ++我读到的语法是Try,catch。我试图这样做,但它不工作。这里是我的代码在c ++:
In c++ I read that the syntax is Try, catch. I am trying to do that, but its not working. here is my code in 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!"
}
如何在c ++中捕获无效的输入?是的,我使用一个头文件为这个类。如果你需要这些内容,让我知道。
How can I catch invalid input in c++? Yes, I am using a header file for this class. If you need those contents, let me know. I will continue to search the web and post if I have found an answer!
推荐答案
您将需要 #include< limits>
int x;
std::cout << "Enter a number: ";
std::cin >> x;
while(std::cin.fail()) {
std::cin.clear();
std::cin.ignore(numeric_limits<streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> x;
}
std::cout << "x = " << x << std::endl;
有一个模板。
这篇关于如何在c ++中捕获无效的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!