kaizoku
kaizoku

Reputation: 19

Why is this loop infinitely repeating?

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?

Upvotes: 0

Views: 94

Answers (2)

glglgl
glglgl

Reputation: 91049

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?

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249163

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.

Upvotes: 1

Related Questions