Tag Archives: programming

How to validate numeric-integer input in C

I had one of my buddies ask me how to validate input in C today... Turns out the task is kind of daunting. I thought I could get away with the following below:

int status, input;
status = scanf("%d", &input);
while(status!=1){
	printf("Incorrect number... please try again: ");
	status = scanf("%d", &input);
}

but the problem is you receive an infinite loop. The reason behind this is when you hit return\enter on your keyboard, a newline character is passed in as input. These extra hidden characters are what is messing with your input and spawning the infinite while loop. Luckily, I was able to parse through the extra characters one-by-one and get something working.

Hopefully this helps someone else!

#include<stdio.h>
int main(void){
	// input	user input -- hopefully a number
	// temp		used to collect garbage characters
	// status	did the user enter a number?
	int input, temp, status;

	printf("Please enter a number: ");
	status = scanf("%d", &input);
	while(status!=1){
		while((temp=getchar()) != EOF && temp != '\n');
		printf("Invalid input... please enter a number: ");
		status = scanf("%d", &input);
	}

	printf("Your number is %d\n",input);
	return 0;
}