我正在学习用C编程,我正在开展一个小项目:图书馆管理软件。我遇到的问题是使搜索功能起作用。我知道如果我处理大量数据,我的代码非常简单且效率低下,但由于情况并非如此,我认为它应该可行。 这是我写的函数:
void search_for_book (FILE *BooksFile) {
BooksFile = fopen("Data.txt", "a+");
char book_title[100], test_book[100], author[100], category[100];
int answer, status, more_books;
more_books: // To search for more books
printf("Type the title of the book you would like to look for:\n");
scanf("%s", book_title);
while(!feof(BooksFile)){
fscanf(BooksFile, "%s", test_book);
if(strcmp(book_title, test_book) == 0) { // strcmp returns zero if strings are equal
printf("The book you informed was found.\n");
printf("Do you want to see its information? Type 1 for yes and 2 for no.\n");
scanf("%d", &answer);
if (answer == 1) { // User wants information
fscanf(BooksFile, "%s", author);
fscanf(BooksFile, "%s", category);
fscanf(BooksFile, "%d", &status);
printf("Book's title: %s\n", book_title);
printf("Book's author: %s\n", author);
printf("Book's category: %s\n", category);
printf("Book's status: %d\n", status);
break;
} else { // User doesn't want information
printf("Would you like to search for another book? Type zero if that's the case.\n");
scanf("%d", &more_books);
if (more_books == 0) {
goto more_books;
}
break;
}
}
}
}
我的代码有什么问题,我该如何解决?当我调用这个函数时,程序只执行printf(要求输入书的标题),然后简单地返回主函数,而不是搜索任何东西。
答案 0 :(得分:0)
答案 1 :(得分:0)
你的代码似乎效率低下,我不知道为什么你在search_for_book
函数中传递文件指针而不是你可以在本地使用并打开它。我已经对你的功能做了一些修改试试吧。
void search_for_book()
{
FILE *BooksFile;
BooksFile = fopen("Data.txt", "r");
char book_title[100], test_book[100], author[100], category[100];
int answer, status, more_books;
while(1)
{
printf("Type the title of the book you would like to look for:\n");
scanf("%s", book_title);
while(!feof(BooksFile))
{
fscanf(BooksFile, "%s", test_book);
if(strcmp(book_title, test_book) == 0)
{
printf("The book you informed was found.\n");
printf("Do you want to see its information? Type 1 for yes and 2 for no.\n");
scanf("%d", &answer);
if (answer == 1)
{
// User wants information
fscanf(BooksFile, "%s", author);
fscanf(BooksFile, "%s", category);
fscanf(BooksFile, "%d", &status);
printf("Book's title: %s\n", book_title);
printf("Book's author: %s\n", author);
printf("Book's category: %s\n", category);
printf("Book's status: %d\n", status);
break;
}
}
}
rewind(BooksFile);
printf("Would you like to search for another book? Type zero if that's the case.\n");
scanf("%d",&more_books);
if(more_books == 1)
continue;
else
break;
}
}