【问题标题】:Variable undeclared even if it was in C program变量未声明,即使它在 C 程序中
【发布时间】:2021-07-30 14:12:39
【问题描述】:

有一个错误表明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);

}

【问题讨论】:

  • struct book; 不完整。你的意思是像struct LIS {/* ... */ } book; 这样的东西吗?也就是说,您是否尝试在book 之前删除; struct

标签: c struct error-handling compiler-errors structure


【解决方案1】:

您应该像这样替换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);

【讨论】:

  • 谢谢!我已经这样做了,现在没有编译器错误。
猜你喜欢
  • 2018-04-19
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 2013-01-16
  • 2021-08-25
相关资源
最近更新 更多