Generate an error if the code entered by the user is not a valid value

0

I have the following code snippet:

       //Pedir para entrar com o código enquanto for menor ou igual a 0
        do{
            printf("Entre com o codigo:");
            scanf("%i",&CODAUX);    
        }while((CODAUX <= 0)) ;

        //Pedir para entrar com o nome enquanto for vazio
        do{
            printf("Entre com o nome:");
            scanf("%s",&NOMAUX);    
        }while(NOMAUX == " ");
  

I would like to know how to validate if the code entered by the user is a   number and not a letter, so I would show an error message saying that the code is invalid   and started the process again.

    
asked by anonymous 01.11.2018 / 17:48

1 answer

0

To manipulate the input, it is recommended to read it as a string, so you will not lose any characters (because if you lose, how will you detect it?). Below is a code I made that reads an entry, and returns -1 if it contains any character that is not between 0-9, or the code itself reported if everything happens fine.

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

int codigo(){
    char codigo[100];

    scanf("%s", &codigo);

    int i;
    for (i = 0; codigo[i] != '
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

int codigo(){
    char codigo[100];

    scanf("%s", &codigo);

    int i;
    for (i = 0; codigo[i] != '%pre%'; i++)
        if (!isdigit(codigo[i]))
            return -1;

    return atoi(codigo);
}

int main(void){
    printf("Codigo: %d\n", codigo());
}
'; i++) if (!isdigit(codigo[i])) return -1; return atoi(codigo); } int main(void){ printf("Codigo: %d\n", codigo()); }
    
03.11.2018 / 04:15