scanf 扫描 C 语言中的奇怪问号

  • 本文关键字:扫描 语言 scanf c scanf
  • 更新时间 :
  • 英文 :


我为一个学校项目编写了这段代码,我遇到了以下问题。当我第一次选择 1 时,我的程序运行良好,但是当我选择 w 或第二次时,出了点问题。两个 ifs 都没有运行。我打印了usr_ans2以查看scanf的结果usr_ans2变量是框中的一个奇怪的问号,而不是我键入的w或r字符。我也试过scanf(" %c", usr_ans2).问号不显示,但 if 命令仍未运行。

int main(){
    int usr_ans1;
    char usr_ans2;
    while(1){
        printf("nSelect action: (1-3)n");
        scanf("%d", &usr_ans1);
        if(usr_ans1 == 1){
            printf("Select to write or read from a file the text: (w/r) ");
            usr_ans2 = scanf("%c", &usr_ans2);
            if(usr_ans2 == 'w')
                printf("You selected to write");
            else if(usr_ans2 == 'r')
                printf("You selected to read");
        }
        else if(usr_ans1 == 2){
            printf("Example1");
        }
        else if(usr_ans1 == 3){
            printf("Example2");
        }
    return 0;
}

usr_ans2 = scanf("%c", &usr_ans2); 中的scanf()将返回 1(成功转换的说明符的数量(或 EOF(一些负值,如文件末尾或发生错误时的 -1(。 if(usr_ans2 == 'w')永远不会是真的。

尝试

// usr_ans2 = scanf("%c", &usr_ans2);
scanf(" %c", &usr_ans2);  // add the space too to skip leading white-space

最新更新