-
Help with inputs
I have a very simple code problem.
Code:
#include <stdlib.h>
#include <stdio.h>
int main (){
int r, c;
while (1){
printf ("Indicate the size of the play board (must be even numbers between 4-20)\nEnter row column: ");
scanf ("%d %d", &r, &c);
if (((r%2) == 0)&& ((c%2)==0)&&(c>=4)&&(c<=20)&&(r>=4)&&(r<=20))
break;
else
printf ("Invalid input. \n\n");
_sleep (500);
}
return 0;
}
Basically i want even numbers between 4-20, and asks again if its not.
However when i enter a symbol, it goes haywire, and it doesn't ask the user and just loop itself.
Why is this and how do i fix this?
-
The f in scanf means "formatted". If your input isn't formatted, then scanf isn't for you. (That is to say, if you don't trust your users to not type letters, then you are going to have to read things in by characters and build the number yourself.)
-
I see! Thanks alot :)! I will use getchar instead
-
You can check the return of scanf. If it is 0, then you know that scanf could not read any numbers. However, you will still have to read in the bogus input, before retrying scanf.
A common approach is to use fgets to read each line, then sscanf to parse it. If a line does not parse right, then you can print an error and retry.