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
")
, but here's a trick to do it:
int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '
')
printf("failure
");
else
printf("valid integer followed by enter key
");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…