0

This simple program has a switch statament that is supposed to go to "default" only if the user doesn't follow the rules. But it goes to "default" anyway after the first run. I cannot explain why.

#include <stdio.h>
#include <windows.h>

int main(){

    char a = 'a'; //I tried to put 'n' here, but it goes to default anyway.

    while (TRUE){

        printf("Type \'n\' for notepad, \'e\' for explorer or \'g\' for both (type \'p\' to exit): ");
        scanf("%c", &a);

        switch (a){
        case 'n':
            system("notepad"); break;
        case 'e':
            system("explorer"); break;
        case 'g':
            system("notepad & explorer"); break;
        case 'p':
            return 0;
        default:
            printf("Something went wrong. Read the instructions carefully.\n");
        }

    }
    return 0;
}
Andreas Wenzel
  • 12,860
  • 3
  • 14
  • 29
catiz
  • 9
  • 1
  • 1
    When you give the input in the terminal, you end it with the `Enter` key, right? That key will be added to the input as a newline `'\n'`. Which will also be read by `scanf` and the `%c` format. The simple solution is to ask `scanf` to ignore *leading* spaces (and newline is considered a space) before you read the character. This is done by assind a single leading space in the format string: `" %c"`. – Some programmer dude Sep 26 '21 at 08:45
  • You're right, it works now! Thank you very much @Someprogrammerdude – catiz Sep 26 '21 at 08:50

0 Answers0