0
votes

I'm using scanf to read in an int, however, I to make create an error if someone puts something other than an int. I have noticed that if I input a character for scanf("%d",%number);, it saves it as 0. I would like 0 to be an option. How do i avoid this issues?

the test code would be int number; scanf("%d",&number); printf("%d",number);

1
Always check what scanf returns. And remember that if scanf fails to match the input to the format, then it will return and leave the input untouched (to be read by the very next call to scanf). That's why it's recommended to read whole lines (using e.g. fgets) and parse it using e.g. sscanf or strtol. - Some programmer dude

1 Answers

1
votes

Try this method to see if the entered input was a number %d:

#include <stdio.h>

int main(void) {
    int number;

    if (scanf("%d", &number))
        printf("A number!\n");
    else
        printf("Not a number!\n");

    return 0;
}