0

how to ask user for input in a switch statement that will generate another switch in c, I tried this but my program crashed.

#include <stdio.h>
#include <stdlib.h>

int main()
{

    char choise1, choise2;

    printf("Starting menu:\n a -> Start\n");
    choise1 = getchar();

    switch(choise1){

    case 'a':
        printf("\n a -> New Game\n b -> Load Game");
        choise2 = getchar();
        switch(choise2){
        case 'a':
            printf("Start new game.");
            break;
        case 'b':
            printf("Loading game.");
            break;
        default:
            printf("This is a wrong input.");
        }
        break;

    default:
        printf("This is a wrong input.");

    }

    return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

1 Answers1

3

The problem here as I see it is due to the remaining input the input buffer.

When you input a and press ENTER, a newline is stored after the a in the input buffer, which will be returned in the next call to getchar().

If you want successive call to getchar() to return the valid inputs, you need to clear the input buffer of the existing content before you can read in next input. Check this answer for some well-explained methods.

That said,

  • getchar() returns an int and for some of the return values, like EOF, it may not fit into a char. Change the choise1 and choise2 types to int.
  • int main() should be int main(void), at least, for a hosted environment to conform to the standard.
Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261