【发布时间】:2016-03-20 12:12:23
【问题描述】:
这是基本结构的代码,但输出与预期不符。有三个 scanf 函数,但只有两个正在执行。中间一个包含垃圾值。
#include <stdio.h>
int main()
{
struct book
{
char name;
float price;
int pages;
};
struct book b1,b2,b3;
printf("Enter names , prices & no of pages of 3 books\n");
scanf("%c%f%d",&b1.name,&b1.price,&b1.pages);
scanf("%c%f%d",&b2.name,&b2.price,&b2.pages);
scanf("%c%f%d",&b3.name,&b3.price,&b3.pages);
printf("And this is what you entered\n");
printf("%c%f%d",b1.name,b1.price,b1.pages);
printf("%c%f%d",b2.name,b2.price,b2.pages);
printf("%c%f%d",b3.name,b3.price,b3.pages);
return 0;
}
【问题讨论】:
-
scanf("%c%f%d"-->scanf(" %c%f%d" -
由于某些缓冲区规则,例如
scanf("%c %d %f", bla, blaa, blaaa);,在数字或浮点数之前提供一些空格 -
需要查看scanf的返回值:
if (scanf("%c%f%d", &b1.name, &b1.price, &b1.pages) != 3) { fprintf(stderr, "Error reading b1 input.\n"); exit(EXIT_FAILURE); } -
跳过前一个换行符。
-
@SCaffrey 输入不完整。它将继续等待非空白的输入。