Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

syntax - How to catch invalid input in c++?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will need to #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(),'
');
    std::cout << "Bad entry.  Enter a NUMBER: ";
    std::cin >> x;
}
std::cout << "x = " << x << std::endl;

There's a template for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...