num
will always contain an integer because it’s an int
. The real problem with your code is that you don’t check the scanf
return value. scanf
returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num
variable did probably not get changed (i.e. still has an arbitrary value because you didn’t initialize it).
As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can’t be simply achieved by scanf("%d\n")
, but here’s a trick to do it:
int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");