我已经尝试了下面编写的代码,但它不起作用。我可以知道为什么吗?是否可以通过结构体指针扫描结构体成员?
#include<stdio.h>
#include<conio.h>
struct book
{
int isdn;
float price;
};
struct book b,*ptr;
void main()
{
clrscr();
b.isdn=10;
b.price=150.75;
printf("\n%d %f",b.isdn,b.price);
ptr=&b;
printf("\n%d %f",ptr->isdn,ptr->price);
scanf("%d %f",&ptr->isdn,&ptr->price); //this statement do not work,why?
printf("\n%d %f",ptr->isdn,ptr->price);
getch();
}
最佳答案
该代码确实有效,并且 scanf 也确实以这种方式工作。我会推荐您阅读一些内容
您读过documentation吗?关于 scanf()
是如何工作的?
您需要完全按照格式字符串指定的方式传入数据。所以在你的情况下:
scanf("%d %f",&ptr->isdn,&ptr->price);
需要传入一个整数、一个空格、一个 float ,例如:
5 2.3
那么 ptr->isdn
将有 5,ptr->price
将有 2.3。如果您没有遇到这种情况,那么这可能不是您的全部代码,或者您可能错过了复制某些内容?
关于我们可以通过结构体指针扫描结构体成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14032453/