如何让 fgets 接收用户输入?

How do I get fgets to receive user input?

我是 C 语言和 Whosebug 的新手。课后我正在做一些练习,但我无法弄清楚这个特定问题。该程序在 fgets 未接收到用户输入的情况下结束。请帮忙

int main(){
printf("Welcome to the Basic Calculator.\nThis lets you input two numbers and the sum will be displayed on the computer screen.\n\n");
double firstNumber;
double secondNumber;
char rating[3];
char feedback[50];
printf("Please enter the first number\n");
scanf("%lf", &firstNumber);
printf("Please enter the second number\n");
scanf("%lf", &secondNumber);
printf("The sum of %f and %f is %f\n\n", firstNumber, secondNumber, firstNumber + secondNumber);
printf("Thank you for using the Basic Calculator. Are you pleased with the result?\n");
scanf("%s", rating);
printf("\nYou said %s. Please provide some feedback.", rating);
fgets(feedback, 50, stdin);
printf("Your feedback is %s. We will improve. Bye!", feedback);

return 0;

}

这是终端的结果: enter image description here

具有“%s”格式的

scanf 读取单个 space 分隔的单词,并在输入缓冲区中的一个读取单词后留下任何 space。

即如果您输入 "good" 的评级并按回车键,scanf 将读取单词 "good" 并在输入缓冲区中保留以下换行符。当您到达 fgets 时,它会读取第一个换行符之前的所有内容,在这种情况下根本什么都没有,因为 fgets 看到的第一件事是 scanf 留下的换行符.

要解决此问题,您可以在调用 fgets.

之前通过 scanf 读取输入缓冲区中剩余的内容,直至并包括换行符。

scanf() 将媒体制作的 \n 留给 stdin/Enter stdin.

您代码中的 scanf() 调用会捕获之前调用中留下的换行符,因为它们会跳过前导白色 space(例如制表符、换行符或纯白色 space)在 stdin 中,但与此相反 fgets() 不会跳过前导白色 space 字符。

此换行符由 fgets() 提取,它停止使用来自 stdin 的输入,直到遇到换行符。

结果是调用 fgets().

只有 \n 换行符

要捕获废弃的换行符,您可以在调用 fgets():

之前使用 getchar();scanf("%*c");
scanf("%s", rating);
printf("\nYou said %s. Please provide some feedback.", rating);

getchar();                         // catching newline character.

fgets(feedback, 50, stdin);

旁注:不要混合调用 fgets()scanf()。使用 fgets() 将所有输入捕获为字符串,然后使用 sscanf() 解析它们,或者始终使用 scanf()