这段代码应该读取书籍信息,然后打印信息,但是我的函数有错误,void in_book(struct books z)
, void out_book(struct books z)
#include <stdio.h>
struct books{
int id;
float price;
char title[15];
char description[140];
};
void in_book(struct books z){
printf("Enter the title\n");
gets(z.title);
printf("Enter the description\n");
gets(z.description);
printf("Enter the id\n");
scanf("%d",&z.id);
printf("Enter the price\n");
scanf("%f",&z.price);
}
void out_book(struct books z){
printf("Title : %s\n",z.title);
printf("Description : %s\n",z.description);
printf("Id : %d\n",z.id);
printf("Price : %.1f\n",z.price);
}
void main(){
struct books b1;
in_book(b1);
out_book(b1);
}
这是输出
Enter the title
book
Enter the description
a book
Enter the id
1234
Enter the price
55
Title :
Description :
Id : 0
Price : 0.0
最佳答案
您正在以按值调用的方式分配结构体每个字段的值,这意味着更改仅在每个函数中可见。如果要设置值以便主函数中的结构保存所有更改,则需要一个指向结构的指针:
struct books *b1 = malloc(sizeof(struct books));
然后传递指针:
in_book(b1);
out_book(b1);
修改函数如下:
void in_book(struct books *z){
printf("Enter the title\n");
gets(z->title);
printf("Enter the description\n");
gets(z->description);
printf("Enter the id\n");
scanf("%d",&z->id);
printf("Enter the price\n");
scanf("%f",&z->price);
}
void out_book(struct books *z){
printf("Title : %s\n",z->title);
printf("Description : %s\n",z->description);
printf("Id : %d\n",z->id);
printf("Price : %.1f\n",z->price);
}
编辑:
您还应该查找主题“按值调用”和“按引用调用”。
关于c - c中的输入输出结构函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45405751/