Search code examples
cstringintegerreturnscanf

C outputs 1 when I key in a string into an int array, how to error handle a non int input?


This piece of code takes in a 7 digit number by a user and returns the same number backwards. However when I enter in a string e.g. "qwerty" it returns me a 1. How do I prevent this from happening and to ensure it works only if user enters a valid 7 digit int?

I have tried using if statements to check the input however it still returns a 1 when I enter a string.

#include <stdio.h>

int main() {
    int num;
    int arr[7];
    printf("Enter a 1-7 digit number: ");
    scanf("%7d", &num);

    while(num){
        for(int i = 6; i >= 0; i--){
            arr[i] = num%10;
            num /= 10;
            if(arr[i]){
                printf("%d", arr[i]);
            }
        }
    }

    return 0;
}

Solution

  • You can check the result of scanf function in order to achieve that, see example below.

        [...]
        printf("Enter a 1-7 digit number: ");
    
        int converted = scanf("%7d", &num);
        if (converted != 1)
        {
            puts("Input error!");
            return -1;
        }
        [...]
    

    For further information, see scanf man page,

    On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.