Scanf("%c %f %d %c") 返回奇怪的值

Scanf("%c %f %d %c") Returning weird values

我的 class 作业要求我提示用户在一个输入行中输入四个变量,char float int char。

完整代码如下:

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

int main(void){
    char h = 'a';
    char b, c, d, e;
    int m, n, o;
    float y, z, x;
    short shrt = SHRT_MAX;
    double inf = HUGE_VAL;

    printf("Program: Data Exercises\n");

    printf("%c\n", h);
    printf("%d\n", h);

    printf("%d\n", shrt);

    printf("%f\n", inf);

    printf("Enter char int char float: ");
    scanf("%c %d %c %f", &b, &m, &c, &y);
    printf("You entered: '%c' %d '%c' %.3f \n", b, m, c, y);

这部分代码是我遇到问题的地方。

    printf("Enter char float int char: ");
    scanf("%c %f %d %c", &d, &z, &n, &e);
    printf("You entered: '%c' %f %d '%c' \n", d, z, n, e);

如果我将上面的部分分离出来,这部分就可以工作了。

    printf("Enter an integer value: ");
    scanf("%d", &o);
    printf("You entered: %15.15d \n", o);

    printf("Enter a float value: ");
    scanf("%f", &x);
    printf("You entered: %15.2f \n", x);

    return 0;
}

鉴于我无法post 图片,因为没有足够高的代表,我将在 运行 程序时提供 link 到控制台的屏幕截图。

如果有人能向我解释程序运行不正常的原因,我将不胜感激。提前致谢。

您在这一行中有错误:

scanf("%c %d %c %f", &b, &m, &c, &y);

您需要在%c之前添加一个space。
试试这一行

scanf(" %c %d %c %f", &b, &m, &c, &y);  // add one space %c
scanf(" %c %f %d %c", &d, &z, &n, &e);

这是因为在您输入数字并按回车后,新行留在缓冲区中,将由下一个scanf处理。

float值的输入在输入流中留下换行符。当下一个 scanf() 读取一个字符时,它会换行,因为 %c 不会跳过白色 space,这与大多数其他转换说明符不同。

您还应该检查 scanf() 中的 return 值;如果您期望 4 个值,但它不是 return 4,那么您遇到了问题。

并且,与 Himanshu says in his 一样,解决该问题的一个有效方法是在格式字符串中的 %c 之前放置一个 space。这将跳过白色 space,例如换行符、制表符和空格,并读取非 space 字符。数字输入和字符串输入自动跳过白色space;只有 %c%[…] (扫描集)和 %n 不跳过白色 space.