Input validation (C)

Soldato
Joined
19 Oct 2002
Posts
2,707
Location
UK
I have to take a number of inputs which must be positive and not exceed a short int, I have been told 'the user must be able to bash their hands on the keyboard and throw the computer out of the window and your program must not break' :o I did the following...

Code:
	do {

		printf("Enter value for x (0-32768): ");
		scanf("%d", &x);

	} while( (x < 0)||(x > 32768) );

But when I put anything in that isn't a number it goes into an infinite loop and I'm not sure why or how to fix it.
 
Let me guess you have not initialised x to be 0 before hand. That will get the ascii value (valid input) of the char though. I.e
int x;
do {
x = 0;
printf("Enter value for x (0-32768): ");
scanf("%d", &x);

} while( (x < 0)||(x > 32768) );

Using scanf is bad as well to be honest.
 
Last edited:
while( (x < 0)||(x > 32768) );

?

while (( x > 0 ) && ( x < 32768 ));

?
 
The point of the loop is to keep asking for the input until an input which meets the requirements is given. If i initialise x as 0 before or change the conditions it won't work. I think I will have to come up with another way to validate.
 
Your problem is that scanf expects the input to be in the given format. If it isn't, it returns an error but doesn't remove the input from the input stream.

So in your case, scanf expects the input to be an integer. If you give it something that isn't an integer, it'll try reading it and fail. Your check in the while condition will fail and it'll try again. Unfortunately the erroneous value will still be in the stream and so it will continue around forever.

I think your best bet will be to read your input in as a string and attempt to convert it using the atoi() function.
 
Just use gets() to read it in as a string, validate it then convert to appropriate format.

Code:
	int x;
	char buff[100];
	do
	{
		printf("Enter value for x (0-32768): ");
		if (fgets(buff,sizeof(buff),stdin) == '\0')
			printf("Must be a number between 0 and 32768");
	}
	while ((x = atoi(buff)) == 0 || (x < 0)||(x > 32768));

There is prolly a better way to do this, but its been a while since I wrote any pure C. Not to mention you should make it so they can't overflow the buffer either.
 
Last edited:
I think you could overflow gets() ?

fgets() is a buffer safe function apparently, except for nulls
or is it getline ?

('tis several millions years since I did C, so could be wrong)
 
Last edited:
Yeah you can overflow gets() like I said above. fgets would be better,forgot about that :P Changed my above code.
 
Last edited:
Back
Top Bottom