我正在使用指针数组来传递输入值到文本文件,但是当我使用fputs时,我不断收到错误“expected const char *”,并且作为指针数组是从名为books的结构中定义的,它的类型是“struct books *”。我尝试使用puts语句,但是这也不能解决问题。最好不要使用指针?将指针值传递给文件c
const char *BOOKS = "books.txt";
struct Books{
int isbn;
char title[25];
char author[20];
char status[10];
}*a[MAX];
int main (void)
{
int i;
printf("Enter the books details that you currently have:\n\n");
for(i=0;i<MAX;i++)
{
printf("Enter the book's isbn number:");
scanf("%d", &a[i]->isbn);
printf("Enter the book's title :");
scanf("%s", &a[i]->title);
printf("Enter the book's author:");
scanf("%s", &a[i]->author);
printf("Enter the book's status, whether you 'have' or whether it is 'borrowed':");
scanf("%s", &a[i]->status);
}
FILE *fp = fopen(BOOKS, "r+");
if (fp == NULL)
{
perror ("Error opening the file");
}
else
{
while(i<MAX )
{
fputs(a[i]->status, fp);
fputs(a[i]->author, fp);
fputs(a[i]->title, fp);
fputs(a[i]->isbn, fp);
}
fclose (fp);
}
}
将指针存储在文件中几乎总是一个非常糟糕的主意。 – Olaf
您制作了一系列指向Book的指针,但您并未将它们指向任何位置。编写'a [i] - > isbn'将引用空指针。相反,使用Book数组会更简单。 –