elvisi27 elvisi27 - 1 year ago 74
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

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

getInt() flowchart


#include <stdio.h>

void clrKyb(void){
char input;
do {
} while(input !='\n');

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



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 Source

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.)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download