【发布时间】:2016-03-13 18:02:42
【问题描述】:
我正在使用指针数组将输入的值传递给文本文件,但是当我使用 fputs 时,我不断收到错误“expected const char*”,并且指针数组是从名为 books 的结构中定义的它属于“struct books *”类型。我尝试使用 puts 语句,但这也不能解决问题。不使用指针会更好吗?
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);
}
}
【问题讨论】:
-
在文件中存储指针几乎总是一个非常糟糕的主意。
-
你创建了一个指向 Book 的指针数组,但你还没有让它们指向任何地方。写
a[i]->isbn取消引用一个空指针。使用 Book 数组会更简单。