Search code examples
cinputinteger

Check if input is integer type in C


The catch is that I cannot use atoi or any other function like that (I'm pretty sure we're supposed to rely on mathematical operations).

 int num; 
 scanf("%d",&num);
 if(/* num is not integer */) {
  printf("enter integer");
  return;
 }

I've tried:

(num*2)/2 == num
num%1==0
if(scanf("%d",&num)!=1)

but none of these worked.

Any ideas?


Solution

  • 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");