char 在 c 中没有按预期工作

char not working as expected in c

您好,考虑下面的简单程序:

int main(void)
{
    //exercise 1

    float num2;
    printf("please enter a number \n");
    scanf_s("%f", &num2);
    printf("the number multiple by 3 is %3.3f\n", num2 * 3);

    //exercise 2
    char ch1, ch2, ch3, ch4;

    printf("enter a word with four char\n");
    ch1 = getchar();
    ch2 = getchar();
    ch3 = getchar();
    ch4 = getchar();

    printf("the chars in reverse order are\n");
    putchar(ch4);
    putchar(ch3);
    putchar(ch2);
    putchar(ch1);
    putchar('\n');
}

输出是:

please enter a number
2
the number multiple by 3 is 6.000
enter a word with four char
ffff
the chars in reverse order are
fff

3 个字符打印到控制台,如果我将练习 2 的代码块移动到 1 上方:

int main(void)
{
    //exercise 2
    char ch1, ch2, ch3, ch4;

    printf("enter a word with four char\n");
    ch1 = getchar();
    ch2 = getchar();
    ch3 = getchar();
    ch4 = getchar();

    printf("the chars in reverse order are\n");
    putchar(ch4);
    putchar(ch3);
    putchar(ch2);
    putchar(ch1);
    putchar('\n');

    //exercise 1

    float num2;
    printf("please enter a number \n");
    scanf_s("%f", &num2);
    printf("the number multiple by 3 is %3.3f\n", num2 * 3);
}

符合预期的结果:

enter a word with four char
ffff
the chars in reverse order are
ffff
please enter a number
2
the number multiple by 3 is 6.000

我想知道为什么当我更改代码块的顺序时它会起作用,我该如何解决,谢谢。

want to know why it's working when i change the order the code block and how can i solve it,

那是因为 scanf_s("%f", &num2); 在输入缓冲区中留下了换行符。因此,您的第一个 getchar(); 会将换行符解释为 ch1.

对于这种情况,getchar 之前的静默会做:

getchar();  // will consume the remaining newline from stdin
ch1 = getchar();
ch2 = getchar();
ch3 = getchar();
ch4 = getchar();

输入第一个浮点数时有一个换行符,调用getchar时输入为char。解决此问题的另一种方法是使用 fgets 将整行作为字符串获取,然后使用您想要的任何格式对其进行解析:

char line[512];
printf("please enter a number \n");
fgets(line, sizeof line, stdin);    // the newline is consumed here
sscanf(line, "%f", &num2);

ch1 = getchar(); // working as expected