I am trying to run an infinite loop which asks for input d or g from the user.
if d or g is not entered I want it to print that it is invalid and just try to get another input. the problem is that sometime it gets stuck even with valid input and sometime when I give one bad input it print the "invalid input" twice.
I tried doing a getchar() in the end because I thought I need to eat the enter. except that did not work. then I though I need a '\n' in the first scanf except that too didn't work.
anyone know what to do?
while(1)
{
puts("Enter g or d\n");
scanf("%c",&c);
switch(c)
{
case'g':
{
puts("Enter two numbers");
//writes 2 numbers on SM
scanf("%d %d", &num1,&num2);
//irellevant code....
break;
}
case'd':
{
puts("Enter one number");
//writes the number received on SM
scanf("%d", &factor_array[0]);
//irrelevant code....
break;
}
default:
printf("Invalid case %c\n",c);
break;
}
}
#include <stdio.h>
int main()
{
char c ;
while( puts( "enter g or d" ) >= 0 &&
scanf( " %c", &c ) == 1 ) // note: the leading space in the format string
// instructs scanf to consume leading white space
{
switch(c)
{
case'g' : case'G' :
puts( "Enter two numbers" );
break ;
case'd' : case'D' :
puts( "Enter one number" );
break ;
default: printf( "Invalid input '%c'\n", c ) ;
}
}
}
By default, the conversion specifier c in "%c" does not skip leading white space characters.
A white space character in the format string causes scanf to first skip over (extract and discard) leading white space characters. scanf( " %c", &c ) ; // skip space, new line etc and read the next non-white-space character into c