2015-04-04 118 views
2

我的班级任务让我提示用户在一个输入行中输入四个变量char float int char。Scanf(“%c%f%d%c”)返回奇怪值

这里是整个代码:

#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; 
} 

看到,因为我不能由于没有足够高的代表发表图片,我会在运行程序时提供一个链接到控制台的屏幕盖。

enter image description here

我真的很感激,如果有人可以给我为什么程序无法正常工作解释。提前致谢。

+0

我编译并运行你的代码,它的工作原理(MSVC)。但我注意到问题陈述和代码之间的类型顺序是不同的。我在一行中输入了所有的值:'输入char int char float:a 1 b 42.9' – 2015-04-04 19:51:25

回答

8

您在此行中有一个错误:

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处理。

+3

额外的解释是有帮助的。 – 2015-04-04 19:53:44

+0

@ Bioniclefreak25,欢迎你:) – Himanshu 2015-04-04 20:13:53

8

float值的输入在输入流中留下换行符。当下一个scanf()读取一个字符时,它会得到换行符,因为%c不会像大多数其他转换说明符那样跳过空白区域。

您还应该检查scanf()的返回值;如果您期望4个值并且它不返回4,那么您遇到了问题。

而且,如Himanshu在他的answer中所述,围绕该问题的有效方法是在格式字符串的%c之前放置空格。这会跳过空白区域,如换行符,制表符和空格,并读取非空格字符。数字输入和字符串输入自动跳过空格;只有%c%[…](扫描集)和%n不会跳过空白区域。

+0

谢谢你的额外解释。我一定会牢记这一点。 – Bioniclefreak25 2015-04-04 20:06:38