我在 C 列表中还是个新手,我遇到了一个大问题...... 首先,我想向您展示我将项目插入列表的代码:
void input_books_info(int number_of_books, BOOK *current)
{
int i;
for(i = 0; i < number_of_books; i++)
{
while(current->next != NULL)
current = current->next;
current->next = (BOOK *)malloc(sizeof(BOOK));
printf_s("%d book catalog number: ", i + 1);
scanf_s("%s", ¤t->next->catalog_number , 20);
printf_s("%d book title: ", i + 1);
scanf_s("%s", current->next->title ,80);
printf_s("%d book author: ", i + 1);
scanf_s("%s", current->next->author ,40);
printf_s("%d book publisher: ", i+1);
scanf_s("%s", current->next->publisher,80);
printf_s("%d book price: ", i + 1);
scanf_s("%f", ¤t->next->price, 5);
printf_s("%d book year published: ", i + 1);
scanf_s("%d", ¤t->next->year_published, 5);
current->next->next = NULL;
printf_s("\n\n");
}
}
这是我的主要功能:
void main (void)
{
int number_of_books, t = 1;
char book_catalog_number[STRMAX];
char book_title[STRMAX];
char book_author[STRMAX];
char reading_file[STRMAX];
char saving_file[STRMAX];
first = malloc(sizeof(BOOK));
first->next = NULL;
/*
printf_s("Enter file name: "); gets(saving_file);
first->next = book_open(first, saving_file);
*/
while(t)
{
char m;
printf_s("1. Input \n0. Exit \n\n");
printf_s("Choose operation: ");
m = getch();
switch(m)
{
case '1':
printf_s("\ninput number of books: ");
scanf_s("%d", &number_of_books);
input_books_info(number_of_books, first);
printf_s("\n");
break;
default:
printf_s("\nNo entry found!\n\n\n\n\n");
break;
}
}
}
最后可能是打印功能的问题:
void print_books_info(BOOK *current)
{
while(current->next != NULL && current != NULL)
{
printf_s("%s, ", current->next->catalog_number);
printf_s("%s, ", current->author);
printf_s("%s, ", current->next->title);
printf_s("%s, ", current->next->author);
printf_s("%s, ", current->next->publisher);
printf_s("%.2f, ", current->next->price);
printf_s("%d", current->next->year_published);
printf_s("\n\n");
current = current->next;
}
}
我的问题是,当我运行应用程序时,程序运行良好。但是当我启动应用程序时,程序只存储第一个输入的数据,第二个和第三个数据丢失了……你能帮我弄清楚吗……???
最佳答案
我怀疑是 scanf_s 读取了比预期更多的字段。相反,使用单个 scanf_s 将整行读入缓冲区,然后使用 sscanf_s 解析缓冲区。
另外,由于没有显示BOOK的声明,所以我们都在盲目拍摄,但是book中的元素是否正确尺寸?否则,读取时会出现元素覆盖。 BOOK 应该看起来像这样:
class BOOK {
BOOK *next;
char catalog_number [20]; // at least 20 chars
char title [80];
char author [40];
char publisher [80];
double price;
int year_published;
};
关于c - C中的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2846194/