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

Scanf(“%c%f%d%c”)返回奇怪的值,c,scanf,C,Scanf,我的类赋值要求我提示用户在一个输入行中输入四个变量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;

我的类赋值要求我提示用户在一个输入行中输入四个变量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 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;
}
由于没有足够高的代表性,我无法发布图像,因此在运行程序时,我将提供一个指向控制台屏幕盖的链接


如果有人能向我解释为什么程序不能正常工作,我将不胜感激。提前感谢。

您在这行有一个错误:

scanf("%c %d %c %f", &b, &m, &c, &y);
您需要在
%c
之前添加一个空格
试试这条线

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

这是因为在输入数字并按ENTER键后,新行保留在缓冲区中,并将由下一个
scanf
处理
浮点值的输入将新行保留在输入流中。当下一个
scanf()
读取字符时,它将获得换行符,因为与大多数其他转换说明符不同,
%c
不会跳过空白

您还应该检查
scanf()
中的返回值;如果您期望4个值,但它不返回4,那么您就有问题了


而且,正如他在书中所说,解决这个问题的一个有效方法是在格式字符串中的
%c
前面加一个空格。这将跳过空格,例如换行符、制表符和空格,并读取非空格字符。数字输入和字符串输入自动跳过空白;只有
%c
%[…]
(扫描集)和
%n
不跳过空格。

我编译并运行了您的代码,代码正常运行(MSVC)。但是我注意到问题陈述和代码之间类型的顺序是不同的。我在一行中输入了所有值:
Enter char int char float:a 1 b 42.9
额外的解释很有帮助。@Bioniclefreak25,欢迎:)谢谢你的额外解释。我一定会记住这一点。
scanf(" %c %d %c %f", &b, &m, &c, &y);  // add one space %c
scanf(" %c %f %d %c", &d, &z, &n, &e);