为什么在 %c 之前需要 space 才能使代码正常工作?

Why does the space is required before %c in order to make the code work?

这真的很有趣

密码错误

#include <stdio.h>

int main( )
{
    char another;
    int num;
    do
    {
        printf("Enter a number: ");
        scanf("%d", &num);
            
        printf("\nWant to enter another number y/n ");
        scanf("%c", &another);
    }while(another == 'y');

    return 0;
}

输出: 输入一个数字:23

想输入另一个号码y/n C:\Users\ShivamSingh\Documents\Let的C\FromBook\Ch3>

要区分错误代码和正确代码,请查看 %c。这两个代码的唯一区别是 space,它位于正确代码中的 %c 之前。

正确密码

#include <stdio.h>

int main( )
{
    char another;
    int num;
    do
    {
        printf("Enter a number: ");
        scanf("%d", &num);
            
        printf("\nWant to enter another number y/n ");
        scanf(" %c", &another);
    }while(another == 'y');

    return 0;
}

输出: 输入一个数字:23

想输入另一个号码y/n是 输入一个数字:54

想输入另一个号码y/nn

scanf() 需要 space 来消耗前一个 scanf()stdin 中留下的待定换行符,后者读取一个数字并在 scanf() 之后立即停止消耗字符最后一位。如果没有这个 space,scanf() 会将下一个字节存储到 another,很可能是用户输入的换行符来提交数字。

请注意,您还应该测试 scanf() 的 return 值以检测无效输入或文件过早结束。