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

Asked

Viewed 51 times

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 resumed the process.

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 a character that is not between 0-9, or the code itself informed if all goes well.

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

int codigo(){
    char codigo[100];

    scanf("%s", &codigo);

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

    return atoi(codigo);
}

int main(void){
    printf("Codigo: %d\n", codigo());
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.