变量未声明,即使它在 C 程序中

Variable undeclared even if it was in C program

有一个错误表明 book 未声明,并且有一条注释显示“每个未声明的标识符对于它出现在的每个函数只报告一次”。但我不明白为什么它只适用于 book.titlestruct 中的其他成员不受影响。

#include<stdio.h>
#include<string.h>

struct LIS
{
  char title[75];
  char author[75];
  char borrower_name[75];
  int days_borrowed;
  float fine;
};

struct book;

void main() {

  int response;

  do {
    printf("Title of the book: ");
    gets(book.title);
    printf("Author(s) of the book: ");
    gets(book.author);
    printf("Name of borrower: ");
    gets(book.borrower_name);
    printf("Number of days borrowed: ");
    scanf("%d", &book.days_borrowed);
    if(book.days_borrowed > 3) { book.fine = 5.00 * (book.days_borrowed-3); }
    else { book.fine = 0; }

    printf("Fine (if applicable): %.2f\n", book.fine);

    printf("Enter any key continue/Enter 0 to end: ");
    scanf("%d\n", &response);
  } while (response != 0);

}

您应该像这样替换 book 定义的代码:

struct LIS
{
char title[75];
char author[75];
char borrower_name[75];
int days_borrowed;
float fine;
} book;

或者像这样:

struct LIS
{
char title[75];
char author[75];
char borrower_name[75];
int days_borrowed;
float fine;
}; 
struct LIS book;

变量book需要结构类型定义。只写struct book;并不能说明book是什么结构。


另外,请注意函数 gets 已从 C 标准中删除,因为它不安全。相反,你应该使用这样的东西:

fgets(book.title,sizeof(book.title),stdin);