#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<io.h>
#define MAXNUM 2000
typedef struct{
char isbn[10];//书序号
char bkName[30];//书名
char author[20];//作者
float price;//单价
int num;//数量
} Book;
int bookNum=3;
Book bk[MAXNUM]={"001","C Primer Plus","Stephen Prata",89.00,10,
"002","python","John zelle",78.00,20,
"003","The Dream of Red Mansion","CaoXueQin",38.00,30};
void myGets(char *ps){
fflush(stdin);
gets(ps);
int seekBkNo(char *bkNo){//查找书籍
int i;
for(i=0;i<bookNum;i++){
if(strcmp(bk[i].isbn,bkNo)==0) break;
}
if(i>=bookNum) return -1;
if(bk[i].num<=0) return -2;
return i;
void input()//图书入库 用书号查找,如果没有则添加。用文件
参考GPT和自己的思路:
好的,您想要的是图书入库的函数。根据您提供的信息,您需要编写一个函数来实现根据书籍的编号来查找书籍,如果库存中不存在该书籍,则添加该书籍,最后更新库存。以下是示例代码:
int inventory(char* bookNo, int amount) { //图书入库
int i, j;
for(i=0; i<bookNum; i++) { //查找书籍
if(strcmp(bk[i].isbn, bookNo)==0) { //找到书籍,更新数量
bk[i].num += amount;
return 0;
}
}
//未找到书籍,需要添加
if(bookNum>=MAXNUM) { //库存已满
printf("Sorry, the inventory is full!\n");
return -1;
}
//添加新书籍
strcpy(bk[bookNum].isbn, bookNo);
printf("Please enter the book name: ");
myGets(bk[bookNum].bkName);
printf("Please enter the author name: ");
myGets(bk[bookNum].author);
printf("Please enter the price: ");
scanf("%f", &bk[bookNum].price);
printf("Please enter the amount: ");
scanf("%d", &bk[bookNum].num);
bookNum++;
return 0;
}
在代码中使用了myGets函数来获取字符串输入,它的实现方式如下:
void myGets(char *ps) {
fflush(stdin); //清空缓存区
gets(ps); //获取字符串
}
使用该函数时需要注意,gets函数存在缓冲区溢出的问题,因此需要先清空缓冲区。