How can I make an error-proof switch?

0

When I make a switch I usually have the worry that someone will introduce an unexpected value such as a letter or a special character, my question is: How can I force the program to only receive what is expected? I had heard that it can be done with a try and catch but I'm not sure and I do not know exactly how it should be.

int cool;
cin>>cool;
//...
switch(cool){
case 1:
 //..
case 2:
 //...
default:
 //...
 }
    
asked by Marco Leslie 25.09.2017 в 21:34
source

1 answer

4
  

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning .

     

- Rick Cook -

Nowadays programming is a race between software engineers striving to create bigger and better idiot-proof programs and the Universe trying to create bigger and better idiots. For now, the Universe is winning.

There is no perfect error-proof algorithm. But C ++ offers tools to detect, control and deal with errors. Unfortunately for you, the switch instruction is not one of those tools.

  

How can I force the program to only receive what is expected?

You can not, the data entry always accepts data. But any unexpected input can be ignored or treated as an error, in the case of your code:

int cool;
cin>>cool;
//...
switch(cool){
case 1:
 cout << "Todo ha ido bien, Mr/Ms 1\n"; break;
case 2:
 cout << "Todo ha ido bien, Mr/Ms 2\n"; break;
default:
 cerr << "Mi nombre es " << cool << " Montoya, introdujiste un numero incorrecto, preparate a morir\n"; break;
 }
  

I had heard that it can be done with a try and catch [...] I do not know exactly how it should be.

The exceptions are one of the C ++ tools to detect, control and deal with errors, in case your code could be used like this:

bool es_correcto()
{
    int cool;
    cin>>cool;

    switch(cool){
    case 1:
        return true;
    case 2:
        return true;
    default:
        throw std::invalid_argument(std::string("Valor ") + std::to_string(cool) + " no reconocido");
    }

    return false;
}

int main()
{
    try
    {
        if (es_correcto()) { /* hacer cosas */ }
    }
    catch (const std::invalid_argument &e)
    {
        std::cout << "Algo ha sucedido en la recoleccion de datos! " << e.what();
    }

    return 0;
}
    
answered by 26.09.2017 / 09:58
source