scanf 不能在 while 循环中工作

Ran*_*vas 1 c file while-loop

我试图在文件中输入一些数字,因此创建了一个 while 循环。输入值后,我询问用户是否希望重复该过程。但是,程序只打印第二个 printf 语句,while 循环终止。该计划是:

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

int main()
{
    FILE *fp;
    fp = fopen("numbers.txt", "w");
    int a;
    char ch = 'y';
    while(ch == 'y')
    {
        printf("Enter the number\n");
        scanf("%d", &a);
        fprintf(fp, "%d", a);
        printf("Do you want to continue?");
        scanf("%c", &ch);                           //doesn't work at all
    }
    fclose(fp);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么第二个 scanf 不起作用?

小智 5

那是因为输入缓冲区中有一个剩余的换行符。

你可以通过在%cin之前给一个空格来消耗它scanf()

scanf(" %c", &ch);
Run Code Online (Sandbox Code Playgroud)

作为旁注

1) 请使用main()for no 命令行参数的标准定义

int main(void)
Run Code Online (Sandbox Code Playgroud)

2) 检查fopen(),scanf()和其他函数调用的返回值。