当我把一个scanf放在一个带有char类型的开关盒里面时,它完全跳过它为什么?

时间:2016-06-25 16:44:21

标签: c char switch-statement scanf

当我将scanf放在带有char类型的开关盒内时,它完全跳过它为什么?它可以工作,如果我将类型更改为int或浮点或任何其他类型,但使用char它只是跳过它。我只是使用此代码作为我面临的问题的一个例子。我正在尝试在case中使用scanf来获取char作为子switch语句的选择。如果重要的话。

next()

2 个答案:

答案 0 :(得分:2)

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

由于之前的scanf \n保留在stdin和第二scanf个商店中,您的变量中并没有等待输入。

答案 1 :(得分:1)

第一次扫描后清除输入缓冲区,它不会读取\n因此第二次读取时缓冲区不干净。
并且始终检查错误

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

您可以使用choice = getch();只读取一个字符而不输入\n或 使用scanf("%c%*c", &choice);读取\n或清除输入缓冲区。

工作示例代码:

#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

另一个工作示例代码:

#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

请参阅:How to clear input buffer in C?