JoseMCabrera
JoseMCabrera

Reputation: 101

How to avoid Input a String in an Integer value using Try Catch (C++)

I just want the user to avoid Input a String in an Integer value using Try Catch because using a while loop does not work at all. I know how to use Try Catch in Java but I do not in C++. I have been trying something like this:

#include <iostream>

using namespace std;

main(){
   int opc;
   bool aux=true;
   do{
   try{
       cout<<"PLEASE INSERT VALUE:"<<endl;
       cin>>opc;
       aux=true;
   }
   catch(int e){
             aux=false;
             throw e;
             cout<<"PLEASE INSERT A VALID OPTION."<<endl;
           }
           }while(aux==false);
       system("PAUSE");
         }//main

Upvotes: 2

Views: 5923

Answers (3)

Eric Z
Eric Z

Reputation: 14505

int opc;
cin >> opc;

The bad bit of the stream will be set when you try to read a non-numeric value. You can check if the stream is in a good state or not. If not, reset the state flags and try the reading again if you want. Note that when the bad bit is set, any following read is ignored. So what you should do before another trial is to first clear the bad bit of the input stream and ignore the rest of the bad input.

// If the input stream is in good state
if (cin >> opc)
{
   cout << opc << endl;
}
else
{
   // Clear the bad state
   cin.clear();

   // Ignore the rest of the line
   cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

// Now if the user enters an integer, it'll be read
cin >> opc;
cout << opc << endl;

Upvotes: 0

AlexD
AlexD

Reputation: 32576

There are easier and better ways to do it, but if you really want exceptions, you could enable them and catch std::ios_base::failure. Something like this:

int main() {
    int opc;
    bool aux = true;
    cin.exceptions(std::istream::failbit);
    do {
        try {
            cout << "PLEASE INSERT VALUE:" << endl;
            cin >> opc;
            aux = true;
        }
        catch (std::ios_base::failure &fail) {
            aux = false;
            cout << "PLEASE INSERT A VALID OPTION." << endl;
            cin.clear();
            std::string tmp;
            getline(cin, tmp);
        }
    } while (aux == false);
    system("PAUSE");
}

Upvotes: 1

Oncaphillis
Oncaphillis

Reputation: 1908

Under normal circumstances the std::cin as all istreams does not throw an exception when the data provided does not fit. The stream changes its internal state to false. So you may simply do something like:

int n;
std::cin >>n;
if(!std::cin) {
 // last read failed either due to I/O error
 // EOF. Or the last stream of chars wasn't
 // a valid number
 std::cout << "This wasn't a number" << std::endl;
}

Upvotes: 0

Related Questions