水深 发表于 2019-12-7 20:32:41

结构体打印问题

为什么结果会多输出一个 书籍编号


#include <stdio.h>
#include <stdlib.h>

struct Book
{
    char name;
    char author;
    struct Book *next;
};

void Input(struct Book *book);
void Input(struct Book *book)
{
    printf("请输入书名\n");
    scanf("%s", book->name);
    printf("请输入书作者\n");
    scanf("%s", book->author);
}

void addbook(struct Book **lib);
void addbook(struct Book **lib)
{
    struct Book *book, *temp;
    book = (struct Book *)malloc(sizeof(struct Book));
    Input(book);
    if(*lib != NULL)
    {
      temp = *lib;
      *lib = book;
      book->next = temp;
    }
    else
    {
      *lib = book;
      book->next = NULL;
    }
}

void printlib(struct Book *book);
void printlib(struct Book *book)
{
    int count = 1;
    while(book != NULL)
    {
      printf("书籍编号:%d\n", count);
      printf("书籍名称:%s\n", book->name);
      printf("书籍作者:%s\n", book->author);
      book = book->next;
      count++;
    }
}

void releaselib(struct Book *book);
void releaselib(struct Book *book)
{
    struct Book *temp;
    while(book != NULL)
    {
      temp = book->next;
      free(book);
      book = temp;
    }
}

int main()
{
    struct Book *lib;
    int ch;

    while(1)
    {
      printf("请问是否需要录入书籍信息(Y/N):\n");
      do
      {
            ch = getchar();
      }
      while(ch != 'Y' && ch != 'N');

      if(ch == 'Y')
            addbook(&lib);
      else
            break;

    }
    printf("请问是否需要打印图书信息(Y/N):");
    do
    {
      ch = getchar();
    }
    while(ch != 'Y' && ch != 'N');

    if(ch == 'Y')
    {
      printlib(lib);
    }
    releaselib(lib);
    return 0;
}
页: [1]
查看完整版本: 结构体打印问题