Need a simple example how to catch a data type error en C++

24 views Asked by At

sorry about my english. I'm trying to do and simple example of raise an exception when input wrong data type in c++, like this in Python:

try:
    x=float(input("Input a real number:"))
    print("Your input:", x)
except ValueError:
    print("Error in data type!, need to be a real number, not char ")

can help me? Thank you in advance.

1

There are 1 answers

0
focaazul On

Well, I found an answer. In c++ don´t need rise an exception like in Python. I propoust this solution, is not perfect, but is close. I say close, because if you input 2,35 ( not 2.35) the output is 2, and it isn't ok, because dot (.) is correct in decimal number, not ( , ) .

#include <iostream>
#define max_size 50 // tamanio maximo de caracteres basura

using namespace std;

int main () {
    float x;
    char basura[max_size];
    cin>>x;
    while (!(cin.good()))
    {
        cout<<"Ud. NO ingresó numeros!!. Reingrese: ";
        cin.clear();// reseteo el bit de error.
        cin.getline(basura,max_size);//leo/limpio el contenido de buffer  max_size  de caracteres
        cin>>x;
    
    }
  cout<<"Ud. ingreso el siguiente numero: "<<x;
  
  return 0;
}