-1

When I put a scanf inside of a switch case with type char it skips it entirely why? It works if I change the type to an int or a float or any other type but with a char it just skips over it. I'm just using this code as an example of the problem im facing. I'm trying to use a scanf inside of a case to get a char to use as selection for a sub switch statement. If it matters.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h.>
#include <stdlib.h>
#define PAUSE system("pause")

main(){
    char choice;
    char switchChoice;

    printf("choose A");
    scanf("%c", &choice);

    switch (choice){
    case 'A':
        printf("see if this works");
        scanf("%c", &switchChoice);
        printf("%c", switchChoice);
        PAUSE;

    }//end switch


}// END MAIN
Pastelitos Slim
  • 23
  • 1
  • 1
  • 2

2 Answers2

2
scanf(" %c", &switchChoice);
       ^ put a space before %c in scanf 

Due to previous scanf \n remains in stdin and second scanf stores that in your variable and doesn't wait for input .

ameyCU
  • 16,489
  • 2
  • 26
  • 41
1

just clear input buffer after first scanf, it not reads \n so buffer is not clean for second read.
and always check for errors:

if (scanf("%c%*c", &choice) != 1) return 1;

you may use choice = getch(); to read just one char without Enter \n or use scanf("%c%*c", &choice); to read \n or clear input buffer.

working sample code:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h.>
#include <stdlib.h>
#define PAUSE system("pause")

main(){
    char choice;
    char switchChoice;

    printf("choose A");
//  scanf("%c%*c", &choice);
    choice = getch();

    switch (choice){
    case 'A':
        printf("see if this works");
        scanf("%c", &switchChoice);
        printf("%c", switchChoice);
        PAUSE;

    }//end switch

}// END MAIN

another working sample code :

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h.>
#include <stdlib.h>
#define PAUSE system("pause")

main(){
    char choice;
    char switchChoice;

    printf("choose A");
    if (scanf("%c%*c", &choice) != 1) return 1;
    switch (choice){
    case 'A':
        printf("see if this works");
        scanf("%c", &switchChoice);
        printf("%c", switchChoice);
        PAUSE;
    }//end switch
}// END MAIN

see: How to clear input buffer in C?

Community
  • 1
  • 1