Search code examples
cstringstring-formatting

Check for characters in input in C


void main(){
    int a;
    scanf("%d",&a); // Need to check there is no character entered
    printf("%d",a);
}

Here if i pass abc it will print 0, if i pass 123abc it will print 123, but i need to throw an error in both the conditions.

Here how to check whether only numbers are being entered as input and to throw an error message if character is entered as input. Is it possible to check keeping int as input datatype or should i use char array and check for isalpha condition by traversing the array.


Solution

  • A code that asks for input again if it is not correct:

    #include <stdio.h>
    
    int main(void)
    {
        int number;
        printf("Your input: ");
        while(scanf("%d", &number)!=1 || getchar()!='\n')
        {
            scanf("%*[^\n]%*c");
            printf("you must enter an integer: ");
        }
    
        printf("%d\n", number);
    
        return 0;
    }
    

    The first scanf makes the entry, the second empties the keyboard buffer. getchar checks that the next character is the enter key.