【发布时间】:2014-07-31 05:02:47
【问题描述】:
我是 C 新手,正在学习结构。我创建了一个简单的结构并尝试在结构变量中通过scanf() 输入输入值,但我只得到部分/垃圾输出。我在这里错过了什么吗?
这是我的原始代码-
#include<stdio.h>
void main()
{
struct book
{
char name;
float price;
int pages;
};
struct book b1,b2,b3;
int i;
printf("\n Enter the names, prices and no. of pages of the 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("\n You have entered: \n");
printf("%c %.2f %d", b1.name,b1.price, b1.pages);
printf("%c %.2f %d", b2.name,b2.price, b2.pages);
printf("%c %.2f %d", b3.name,b3.price, b3.pages);
}
这是一组输出-
Enter names, prices & no. of pages of 3 books
A 230.5 13
B 345.9 33
And this is what you entered
A 230.50 13
0.00 3
B 345.89 33
如你所见:
- 一旦我输入第二个
structure variable(b2)的信息,printf()就会停止工作并且不接受信息。关于第三个structure variable(b3) - 当它突然停止通过
scanf()接受值时,我在第二行得到一些垃圾值-0.00 3
我想也许结构定义应该总是在main()之外,所以我什至修改它以在main()之外定义struct book并在main()中声明变量struct book b1,b2,b3;,但它没有任何效果。
我在这里做错了什么?
更新-
我知道在 SO here 上存在类似的答案,但这里的问题是 addressof(&) 运算符不包含在 scanf() 中
【问题讨论】:
-
您是先前输入的尾随换行符的受害者。您需要一种从输入缓冲区中删除(吃掉它)的方法。
-
那么,我应该使用 fflush(stdin) 之类的东西吗?
-
@DarkKnight
fflush(stdin)没有在标准 C 中定义。即使它可以在您的机器上运行,使用它也会使您的程序不可移植。 -
哦,我明白了。那我该如何摆脱尾随的换行符呢?
-
@DarkKnight
void eat_newline(){int c; while((c = getchar()) != '\n' && c != EOF) ;}或更好的选择,请参阅 YuHao 回答