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
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!"
}
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!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…