Simple scanf

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
	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;
		}
		
		
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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 ) ;
        }
    }
}
Could you please go into more detail of the space in the beginning of the scanf?
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

More information: https://en.cppreference.com/w/cpp/io/c/fscanf#Notes
Topic archived. No new replies allowed.