gpt4 book ai didi

c - 如何从 C 函数内部将变量扫描到数据结构中

转载 作者:行者123 更新时间:2023-11-30 19:08:34 25 4
gpt4 key购买 nike

#include <stdio.h>
#define MAX_TITLE_SIZE 20
#define MAX_BOOKS 10

struct Book{
int _isbn;
float _price;
int _year;
char _title[MAX_TITLE_SIZE];
int _qty;
};

void displayInventory(const struct Book book[], const int size){

int i;

printf("===================================================\n");
printf("ISBN Title Year Price Quantity\n");
printf("---------+------------------+----+-------+--------\n");

//iterate through objects
if(size == 0){
printf("The inventory is empty!\n");
printf("===================================================");
}
else{
for(i = 0; i < size; i++){
printf("%-10.0d%-18s%5d $%-8.2f%-8d\n", book[i]._isbn, book[i]._title, book[i]._year, book[i]._price, book[i]._qty);
}
}
}

void addBook(struct Book book[], int *size){

if(*size == MAX_BOOKS){
printf("the inventory is full\n");
}
else{

//increment inventory size
(*size)++; //*size will move the pointer to the next in position/hashcode
//++*size also works



printf("ISBN:");
scanf("%d", book[*size]._isbn);
printf("Title:");
scanf("%s", book[*size]._title);
printf("Year:");
scanf("%d", book[*size]._year);
printf("Price:");
scanf("%f", book[*size]._price);
printf("Quantity:");
scanf("%d", book[*size]._qty);

printf("The book is sucessfully added to the inventory.\n");
printf("\n");
}
}

int main(void){

int size = 0;
struct Book book[MAX_BOOKS];

book[0]._isbn = 1234;
printf("Create string: ");
scanf("%s", book[0]._title);
book[0]._year = 1992;
book[0]._price = 192.90;
book[0]._qty = 2;

size++;

addBook(book, &size);

displayInventory(book, size);
return 0;
}

所以我正在尝试制作这个簿记系统,我想做的是将一本新书添加到 book[] 数组结构中。

当我尝试在 addBook() 函数中输入一本书的 ISBN 时,整个应用程序以非零状态结束。

如何从函数写入数据结构?如果这是一个愚蠢的问题,我很抱歉,但我已经被这个问题困扰了一段时间了。

我做错了什么?

这是 repl.it 的链接:https://repl.it/JRPH/4

最佳答案

使用scanf时应该引用变量的地址。具体来说, scanf("%d", book[*size]._isbn); -> scanf("%d", &(book[*size]._isbn)); 等等...

看看this .

关于c - 如何从 C 函数内部将变量扫描到数据结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44961624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com