有人可以解决这个代码块吗?

时间:2016-03-06 11:40:45

标签: c scanf

为我解决这个因为我真的不知道

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

int main() {
    char ans;

    printf("1. The patients felt _____ after taking the medicine.\n");
    printf("\t a. best\n\t b. better\n\t c. good\n\n");
    scanf("%c", &ans);

    if (ans == 'b') {
        printf("2. I ______ my essay by the time the bell rings.\n");
        printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n");
        scanf("%c", &ans);
    } else {
        printf("YOU FAILED!");
    };
    return 0;
}

如果您回答第一个问题,请继续下一个问题并回答第二个问题,但问题是我无法输入答案,即使有scanf

2 个答案:

答案 0 :(得分:2)

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

int main() {
    char ans;

    printf("1. The patients felt _____ after taking the medicine.\n");
    printf("\t a. best\n\t b. better\n\t c. good\n\n");
    scanf("%c", &ans);

    if (ans == 'b') {
        printf("2. I ______ my essay by the time the bell rings.\n");
        printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n");
        scanf(" %c", &ans);
    } else {
        printf("YOU FAILED!");
    };

    return 0;
}

区别在于:

scanf(" %c",&ans);
       ^ this space this will read whitespace characters (which newline also is)
         until it finds a non space character.

scanf没有使用第一个\n调用中保留在缓冲区中的scanf字符。

我试试这个,它有效!

答案 1 :(得分:1)

第二个scanf("%c"...)读取第一个scanf在标准输入中保留挂起的换行符。您可以通过以下方式阅读额外的字符来解决此问题:

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

int main() {
    char ans;

    printf("1. The patients felt _____ after taking the medicine.\n");
    printf("\t a. best\n\t b. better\n\t c. good\n\n");
    scanf("%c%*c", &ans);

    if (ans == 'b') {
        printf("2. I ______ my essay by the time the bell rings.\n");
        printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n");
        scanf("%c%*c", &ans);
    } else {
        printf("YOU FAILED!");
    }
    return 0;
}

scanf("%c%*c", &ans)读取一个字符并将其存储到ans变量中,然后它读取另一个字符并将其丢弃。这样,\n之后用户键入的b将被丢弃。

另一种方法是使用scanf(" %c", &ans)忽略空格字符:格式的scanf指示scanf读取并忽略任何空格字符。第一种方法的优点是,如果用户输入单个字符后跟输入,scanf之后没有任何字符待处理,第二种方法会使\n处于待处理状态,但它会被忽略以下scanf

相关问题