Home > database >  C Programming int validation
C Programming int validation

Time:11-08

int main() {
    int choice;
    printf("\n----------Welcome to Coffee Shop----------");
    printf("\n\n\t1. Login   ");
    printf("\n\t2. Sign Up ");
    printf("\n\nPlease enter 1 or 2: ");
    scanf(" %d", &choice);
    system("cls||clear");
    
    //put while loop to check
    switch (choice) {
    case 1:
        system("cls||clear");
        login();
        break;
    case 2:
        system("cls||clear");
        user_signup();
        break;
    default:
        printf("\nInvalid Number\n");
        main();
        break;
    }

    return 0;
}

How do i make user retype their input if the input is not int? I tried to use isdigit() but it wont work, May i know what are the solutions?

CodePudding user response:

I think it would be better to receive it as a string and check if all chars are numbers. And if all the chars are numbers, they convert them to int

like this number = number * 10 chars[n] - '0';

CodePudding user response:

scanf returns the number of input items successfully matched. So you can build a loop that runs until you get exactly one item.

A very simple approach would be:

while(1)
{
    int res = scanf(" %d", &choice);

    if (res == 1) break;  // Done... the input was an int

    if (res == EOF) exit(1); // Error so exit

    getchar();  // Remove an discard the first character in stdin
                // as it is not part of an int
}

printf("Now choice is an int with value %d\n", choice);

That said, I recommend that you take a look at fgets and sscanf. They are often a better approach than scanf

CodePudding user response:

The scanf() function returns the number of fields that were successfully converted and assigned. So in your scanf(" %d", &choice); line, you can do this:

do {
    printf("\n\nPlease enter 1 or 2: ");
    int result=scanf(" %d", &choice);
    if (result==1) {
        break;
    }
    printf("\nInvalid Number\n");
} while (1);
  • Related