3

I have written the following switch-case:

    char input;
    int run = 1;
    while(run){
        printf("Would you like to update the student's name? Enter Y or N (Y=yes, N=no)\n");
        input = getchar();
        switch (input)
        {
        case 'N':
            run = 0;
            break;
        case 'n':
            run = 0;
            break;
        case 'Y':
            printf("Please enter the updated name\n");
            scanf("%s", st->name);
            run = 0;
            break;
        case 'y':
            printf("Please enter the updated name\n");
            scanf("%s", st->name);
            run = 0;
            break;
        case '\n':
            break;
        default:
            printf("Wrong input. Please enter a valid input (Y or N)\n");
        }
    }

When I run it does this:

Please enter the id of the student that you would like to update
1
Would you like to update the student's name? Enter Y or N (Y=yes, N=no)
Would you like to update the student's name? Enter Y or N (Y=yes, N=no)

Why does it print the question twice? Can anyone help? Other than that the cases run as expected.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    You've got the `'\n'` from the 1st question (answer was `"1\n"`). Don't mix `scanf()` and `getchar()`. Always prefer `fgets()` for user input. – pmg May 02 '20 at 11:44

1 Answers1

3

The function getchar reads all characters including new line characters. Instead use

scanf( " %c", &input );

Also your switch statement has a duplicated code. Write for example

    switch (input)
    {
    case 'N':
    case 'n':
        run = 0;
        break;
    case 'Y':
    case 'y':
        printf("Please enter the updated name\n");
        scanf("%s", st->name);
        run = 0;
        break;
   //...

The same approach you can use for other labels of the switch statement. and remove this code

    case '\n':
        break;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335