这是基本结构的代码,但输出不符合预期。有三个 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", &bx.name, &bx.price, &bx.pages);
至
scanf(" %c%f%d", &b1.name, &b1.price, &b1.pages);
按Enter后,stdin
中会留下一个“\n”,稍后将被“%c”消耗。读取字符 ('\n') 后,scanf()
需要一个 float ,如格式字符串中的“%f”所示。然而,它没有得到所需的 float ,而是遇到了一个字符,然后悲伤地返回了。因此,&bx.price
和 &bx.pages
不会更新,因此它们保持未初始化状态,为您提供垃圾值。
如果 scanf()
中存在前导空格,则在读取开始之前将丢弃所有空白字符(如果有)。由于\n
被丢弃,接下来的读取过程将(大概)成功。
另外,还有一个提示:始终检查 scanf()
的返回值,因为您永远不知道用户将输入什么内容。
示例代码:
#include <stdio.h>
struct book
{
char name;
float price;
int pages;
};
int main()
{
struct book b1, b2, ..., bx;
printf("Enter names, prices & no of pages of x books:\n");
while (scanf(" %c%f%d", &bx.name, &bx.price, &bx.pages) != 3)
{
fputs("Error reading bx. Please try again:\n", stderr);
scanf("%*[^\n] ");
}
......
printf("And this is what you have entered:\n");
printf("%c %f %d", bx.name, bx.price, bx.pages);
......
return 0;
}
输入和输出示例:
Enter names, prices & no of pages of x books:
asd wedewc efcew
Error reading bx. Please try again:
a 12.34 42
And this is what you have entered:
a 12.340000 42
关于c - 三个 scanf 导致两个并获取垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113511/