How to make a wrong user entry not bug the program?

5

Example, I declare the menu option as int , hence the little bug goes there and types a letter or a special character and this will make the program bugar. The question is: can you solve this?

Example:

int opc;
printf("Digite uma opção");
scanf("%d", &opc);

When the guy type letter, broken number or special character goes bugar.

    
asked by anonymous 13.06.2015 / 15:28

1 answer

5

Checks the value returned by scanf() :

if (scanf("%d", &opc) != 1) /* erro */

Better yet to use fgets() followed by sscanf() :

char tmp[20];
if (!fgets(tmp, sizeof tmp, stdin)) /* erro */;
if (sscanf(tmp, "%d", &opc) != 1) /* erro */;

Edit

In this last code I entered the variable tmp to have a temporary place where to save the input of the user in characters until it turns into number.

fgets() reads these user characters and puts them in tmp . The value returned by fgets() is the address of tmp , except in case of error when fgets() returns NULL . This is what if checks, if there was an error while processing fgets() .

if (!fgets(...)) /* ... */;
// estas duas pseudo instruções são iguais
if (fgets(...) == NULL) /* ... */;

sscanf() functions as scanf() . The difference is in the input. The scanf() receives input from stdin (from the keyboard); sscanf() receives input of a string (the string that the user wrote and that is stored in tmp ). In either case the value that scanf() (or sscanf() ) returns is the value of the assignments made, or EOF in case of error. In our case we have only 1 possible assignment, so we only have 3 possible return values for sscanf() . Or it returns 1 which means that the statement went well it assigned the value to the variable opc ; or returns 0 which means that it could not assign value (for example the user wrote "twenty"); or even devovle EOF to indicate internal function error.
In other words, anything except 1 does not interest us.

int chk = sscanf(tmp, "%d", &opc);
if (chk == EOF)  /* erro interno */;
if (chk == 0) /* input com erro */;
if (chk == 1) /* tudo ok */;
    
13.06.2015 / 15:31