在我为图书数据库程序编写的这个函数中,我让用户输入一个图书标识符,然后它应该去搜索该图书的链表并显示它的详细信息。
identifierTemp 变量初始化为 NULL 但当用户输入他们想要的图书标识符时,identifierTemp 保持为 NULL?!?!
这是函数。希望有人能发现我的错误。提前致谢。
void viewBook() {
printf("\n*** VIEW A BOOK ***\n");
struct node *currentBook, *prevBook;
bool notFound = true;
char* identifierTemp = NULL;
//user input
printf("\nBook Identifier: ");
scanf("%s", identifierTemp);
fflush(stdin);
printf("\n");
if (isEmpty())
printf("Error - there are no books in the list\n\n\n");
else {
currentBook = prevBook = firstBook;
while (notFound && currentBook != NULL) {
if (identifierTemp == currentBook->element->identifier)
notFound = false;
else {
prevBook = currentBook;
currentBook = currentBook->next;
}//end else
} //end while
if (notFound)
printf("Error - there is not such book with the identifier %s\n\n\n", identifierTemp);
else {
//DISPLAY ALL BOOK DETAILS
printf("\n\nIdentifier: %s", currentBook->element->identifier);
printf("\nTitle: %s", currentBook->element->title);
printf("\nAuthor: %s", currentBook->element->author);
printf("\nYear: %d", currentBook->element->year);
printf("\nStatus (1 = not available to take out): %d", currentBook->element->status);
printf("\nCustomer: %s", currentBook->element->customer);
printf("\nTimes Taken Out: %d", currentBook->element->timesTakenOut);
printf("\nGenre: %s", currentBook->element->genre);
} //end else
printf("\n");
}//end else
menuSystem();//return to the menu
}//end ViewBook
控制台输出:
*** VIEW A BOOK ***
Book Identifier: *USER INPUT HERE*
Error - there is no such book with the identifier (null)
最佳答案
你需要给 identifierTemp
一些内存,这样 scanf
就有地方放数据了
即改成
char identifierTemp[4096]; // Or some other size that can reasonably store the string.
重新阅读scanf
的手册页,这样就不会超过限制
关于Char* 在不应该的时候显示 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28974184/