I am trying to make a function to check the input of the user and let them try again in case they enter a wrong kind of input.
So when I enter a wrong input into the function it throws me inside an infinite loop. What can I do to fix it?
I am allowed to use only getchar
and scanf
for user input.
int sizeOfField()
{
int size,inputCheck,flag=0;
while (!flag)
{
inputCheck= scanf(" %d ", &size );
if ( inputCheck < 1 )
{
printf( "Invalid Input!\n" );
printf( "Try agian");
} else if (inputCheck == 1)
flag=1;
}
return size;
}
Using
fgets()
would be better. But to live with that restriction ....When
scanf(" %d ", &size );
returns 0, the non-numeric input remains instdin
.Code needs to consume the invalid input - that is missing from OP's code.
For consistency, even with good input, consume the rest of the line too. This code does not detect if trailing junk exists after the good input on the same line.
The 2nd space in
" %d "
is also a problem. A" "
directsscanf()
to read all white space until some non white space is detected. This meansscanf(" %d ", &size );
will not return until something like"123\n4\n"
is entered. The4
is read, determined not to be a white space and put back for later input. Drop the trailing white-space from the format.Code also has a problem should an input return
EOF
(end-of-file or rare input error). The functionsizeOfField()
has no way to convey end-of-file. Function could be re-defined or for now, simple exit the program.Curiously this is a case where" %d"
has benefit over"%d"
. When input is non-numeric, code is certain at least all leading white space (including'\n'
) are consumed. The specifications about what charterers are put back due to being non-numeric intostdin
are problematic if more that one character needs to be "put back" intostdin
. Without that assurance,while ((ch = getchar()) != '\n' && ch != EOF);
may not consume all the offending non-numeric input.