我正在使用指針數組來傳遞輸入值到文本文件,但是當我使用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數組會更簡單。 –