I have been stuck up with this issue. The requirement of the problem is very simple. All I want to do is check user input and allow the user to enter only lower case letters. The other constraint is I want to do it using only scanf(). I know I can use gets() and other input functions, but still, for the sake of understanding it better, I would like to use scanf() to do so.
I have tried the following on GCC:
char str[100000];
return_value=scanf("%99999[a-z]",str);
if(return_value==0 || return_value==EOF)
{
printf("illegal input");
}
else
printf("input accepted");
The following works absolutely as expected. So if the user tries to enter any string in upper case letters the code simply prints out: "illegal input".
The problem comes up when i try to put the above code in a finite while loop. For example:
int counter=0;
char str[100000];
scanf("%2d",&counter);
while(counter>0)
{
fflush(stdin);
return_value=scanf("%99999[a-z]",str); //note
if(return_value==0 || return_value==EOF)
{
printf("illegal input");
}
else
printf("input accepted");
counter--;
}//end of while
In the above case as soon as user enters the value of the variable "counter" and presses the return key, the control straight away goes and prints "illegal input", without even waiting for the user to input a string.
To correct this error I tried putting the following in place of the line marked as note:
return_value=scanf("%99999s[a-z]",str); //note
or even this:
return_value=scanf("%99999c[a-z]",str); //note
In either case although the user is allowed to enter the input string after entering the 'counter' variable's value, the user input sanitization is not done, i.e even if the user enters a string consisting of uppercase characters, the output is not "illegal input" (as it should have been) but rather "input accepted".
Now can some one please explain this to me. Where am i going wrong or am i simply overlooking something and doing some silly mistake?