gpt4 book ai didi

c - 我的C程序在启动时一直崩溃

转载 作者:行者123 更新时间:2023-12-02 07:15:10 26 4
gpt4 key购买 nike

我正在为一个简单的库制作c程序,但是由于某种原因,该程序在启动时一直崩溃。就像有一个显示的菜单,但它什至没有出现,只是崩溃了。谁能帮我?

struct library
{
char name[50];
int id;
int qty;
}books[50],copy[50],delet[50],sort[50];
int i=0;
FILE *mybooks;

int main()
{
int choice; char ans;
int id;
int qty;
int s,o=0,j=0;
char name[50];
mybooks=fopen("D:\\mybooks.txt","r");
if (mybooks == NULL) printf("Error. File not found.");
else
{
while(!feof(mybooks))
{
fscanf(mybooks,"%[^\n] %d %d",books[i].name,&books[i].id,&books[i].qty);
strcpy(copy[i].name,books[i].name);
copy[i].id=books[i].id;
copy[i].qty=books[i].qty;
i++;
}
fclose(mybooks);
}
printf("Welcome to the Library.\n");
do
{

printf("Please choose an option:\n");
printf("1.Insert a book\n");
printf("2.Delete a book\n");
printf("3.Search a book by ID\n");
printf("4.Search a book by name\n");
printf("5.Display all books (sorted by name)\n");
printf("6.Display all books (unsorted)\n");
scanf("%d",&choice);
switch (choice){
case 1:
printf("You will need to enter a name, ID, and quantity of the book.\n");
printf("please enter book name:");
fflush(stdin);
fgets(name,sizeof name,stdin);
printf("please enter book ID:");
scanf("%d",&id);
printf("please enter book quantity:");
scanf("%d",&qty);
InsertBook(name,id,qty);
printf("your book has been added successfully\n");
break;
case 2:
printf("Please enter book ID:");
scanf("%d",&id);
DeleteBook(id);
printf("book successfully deleted.\n");
break;
case 3:
printf("Please enter ID of Book:");
scanf("%d",&id);
s=LinearSearch(id,j);
if (s>=0)
{
printf("Book Found.\n");
printf("Name:%s",books[s].name);
printf("ID:%d\n",books[s].id);
printf("Quantity:%d\n",books[s].qty);
}
else
printf("Sorry, the book doesn't exist.\n");
break;
case 4:
printf("Please enter name of book:");
fflush(stdin);
gets(name);
sorting();
s=BinarySearch(name,0,i);
printf("Book Found.\n");
printf("ID:%d\n",sort[s].id);
printf("Quantity:%d\n",sort[s].qty);
break;
case 5:
sorting();
while (o<i);
{
printf("%s\n",sort[o].name);
o++;
}
printf("\n");
break;
case 6:
while(o<i)
{
printf("%s",books[o].name);
o++;
}
break;
default:
printf("Invalid Choice. Please try again.\n");
break;
}
printf("do you want to choose another option?(y/n) ");
scanf(" %c",&ans);
}while(ans == 'y');
}

(我正在为库使用函数,但由于我尚未调用它们,所以我认为它们不会引起任何问题。)
编辑了问题以添加结构

最佳答案

在输入文件上执行任何I / O之前,您已经测试了文件结束条件。然后,当您使用fscanf()执行I / O时,您没有测试结果是否可以成功读取变量。

发生的情况是scanf()可能失败并且您没有到达循环的末尾,即EOF条件。您被困在那里,直到您的一项分配(strcpy(copy[i].name,books[i].name);copy[i].id=books[i].id;copy[i].qty=books[i].qty;)最终导致溢出。

要验证这一点,请在调试器中运行代码。

使用fscanf()非常棘手,请始终对其进行全面测试。

关于c - 我的C程序在启动时一直崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62180932/

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