3

Here is the while loop and switch in question (track1 defines a bigger loop not shown here):

while (track6 ==1)
    {
    printf ("would you like to play again? Y or N?\n");
    scanf ("%c", &response);

        switch (response)
            {
            case 'Y' : track6 = 2; 
                break;
            case 'N' : printf ("thanks for playing!\n");
                            track6 = 2, track1 = 2;
                break;
                    default : printf ("response is case-sensitive and must be either Y or N. your response is invalid. please reenter.\n");
            }
    }

The output I receive is:

would you like to play again? Y or N?

response is case-sensitive and must be either Y or N. your response is invalid. please  reenter.

would you like to play again? Y or N?

(prompts for input and then executes correctly)

Seems like it is executing the first printf, skipping the scanf, executing the default, going back to the top of the loop and running properly from there. Any idea why? This is only my 3rd week programming so layman's terms are appreciated.

haccks
  • 104,019
  • 25
  • 176
  • 264

4 Answers4

2

I think it's issue with scanf as it reads enter first - try getchar() or add a space character in scanf like " %c"

scanf (" %c", &response);  
Shumail
  • 3,103
  • 4
  • 28
  • 35
1

Seems like it is executing the first printf, skipping the scanf, executing the default, going back to the top of the loop and running properly from there. Any idea why?

No. Seems like it is executing the first printf statement, reading the newline (\n) character left behind by the previous scanf, going back to the top of the loop and running properly from there. One possible solution to eat up this newline character is to change

scanf ("%c", &response);

to

scanf (" %c", &response);  
        ^
        |
   add a space here to eat up '\n'  

But this will work if and only if input from the user is either Y or N. If in case a user input YES or NO, more than one character (excluding \n) then your program should have to eat all these extra character to run the program properly. For this, use a loop just after the scanf in while;

 printf ("would you like to play again? Y or N?\n");
 scanf ("%c", &response);
 while ((response = getchar()) != '\n' && response != EOF) 
     ;
haccks
  • 104,019
  • 25
  • 176
  • 264
1

With

scanf ("%c", &response); you need to skip trailing newline from previous scanf

So use:

int ch;
while ((ch = getchar()) != '\n' && ch != EOF); //eats '\n' 

after scanf

P0W
  • 46,614
  • 9
  • 72
  • 119
0

You need to flush the input buffer before using scanf to input a character.Use simply getchar().It'll eat the '\n' character present in the buffer.

The Game
  • 62
  • 6