0

The purpose of this program is to count the digits in an alphanumeric input. However, I used a loop to not execute the program unless the input is alphanumeric.

This is the code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>

int main(){
   int input,isanum,digitcount;
   printf("\nEnter a number: ");
   scanf("%d",&input);
   isanum=isalnum(input);

   while(isanum==0){
     printf("\nIncorrect input. Try again: ");
     scanf("%d",&input);
     isanum=isalnum(input);
   }
   digitcount=0;
   while(input!=0){
       input=input/10;
       digitcount++;
   }
   printf("\nNumber of digits = %d",digitcount);
   return 0;
}

The problem is with the loop. It keeps looping infinitely and ignores the scanf statement and I don't know why. Am I using isalnum() incorrectly here?

dragosht
  • 3,237
  • 2
  • 23
  • 32
kaizoku
  • 21
  • 1
  • 6
  • Check out [this](http://stackoverflow.com/questions/8464620/program-doesnt-wait-for-user-input-with-scanfc-yn) thread. – DanZimm Mar 05 '15 at 07:27
  • You probably want to read characters with scanf, not integers. Otherwise, it doesn't make any sense to call isalnum. – Lundin Mar 05 '15 at 07:38

2 Answers2

1

You need to check the return value of scanf().

isalnum() takes a character, but you are passing an int. '1' is not the same as 1 in C.

You probably should consume an entire line each time, e.g. with fgets(), and then check if it fits your desired input format, e.g. with sscanf().

As it stands, you never consume anything, you just keep trying to read a number but there isn't one there so it fails every time. Failing to check the return value of scanf() is a contributing factor to your not noticing this.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • You're right. But I'm not exactly familiar with fgets() and sscanf(), could you elaborate more on how I could use them to accomplish this? – kaizoku Mar 05 '15 at 07:40
  • You use `fgets()` to read one entire line. Then you pass that line to `sscanf()` or whatever other function you want, such as `strtol()` if you only want to read a single integer (it's just a simpler way than `sscanf()`). This lets you ensure that you read a single line each time, which is probably more in line with user expectations. – John Zwinck Mar 05 '15 at 07:41
0

Look at how isalnum() is defined: it expects a char *. You, however, give it an int *. The data is stored completely different there.

Besides, if you are reading in an int, you know beforehand that it will be alphanumeric, right?

glglgl
  • 89,107
  • 13
  • 149
  • 217