elvisi27 elvisi27 - 1 month ago 7
C Question

integer validation gives infinite loop

The user needs to type an integer, then type enter. If it gets validated then it should return the integer, if not validated the user should get an error message.

When I try to validate input through

getInt()
function, I get an infinite loop when I type 1 or more chars. When I type
abc
, I get an infinite loop of error messages, while entering
1a
gets the correct validation (1 single error message). I followed the directions of this flowchart:

getInt() flowchart

Code



#include <stdio.h>

void clrKyb(void){
char input;
do {
scanf("%c",&input);
} while(input !='\n');
}

int getInt(void){
char NL= 'x' ;
int value ;

while(NL!='\n'){

scanf("%d%c",&value,&NL);

if(NL!='\n') {

void clrKyb(void);
printf("Invalid integer, please try again:");

}

}
return value ;
}


int main(void) {
int iVal;

printf("Enter an integer: ");
iVal = getInt();
printf("You entered: %d\n", iVal);

return 0;
}

Answer

As noted in comments:

cxw said:

  • In getInt, void clrKyb(void); should just be clrKyb();, since you are wanting to use the clrKyb you have already defined.

Jonathan Leffler said:

  • Note that in clrKyB() (and getInt()), you need to check the return value from scanf(). If it returns EOF, then no amount of retrying etc is going to stop an infinite loop. (As cxw notes, in getInt() at the moment, you (re)declare clrKyB() and don't call it — that's also a problem.)