2016-03-13 142 views
0

我正在使用指针数组来传递输入值到文本文件,但是当我使用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);  
} 
} 
+1

将指针存储在文件中几乎总是一个非常糟糕的主意。 – Olaf

+0

您制作了一系列指向Book的指针,但您并未将它们指向任何位置。编写'a [i] - > isbn'将引用空指针。相反,使用Book数组会更简单。 –

回答

0

您好我已经修改了你的程序如下, 请看看,

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; 
    char *ISBN; 
    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); 
    } 

    i = 0; 

    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); 
      itoa(a[i].isbn,ISBN,10); // Convert the isbn no to const char* in decimal format. to write in to the file. 
      fputs(ISBN, fp); 
      i++; //Increment 'i' to access all the elements 
     } 
     fclose (fp); 
    } 
    return 0; 
} 

希望这有助于。

+0

您应该解释您所做的更改以及原因 –

1

假设你还没有给出完整的代码,到目前为止我明白你想把结构元素写到你已经打开的FILE中。 在你for循环中,您需要使用fputs一些事情如下,

fputs(a[i].title, fp); 
fputs(a[i].author, fp); 
fputs(a[i].status, fp); 

那么就应该有任何错误的工作。 希望有帮助。

+0

我只是试过这个,我仍然得到相同的错误。是的,你写了,我想写结构元素到我打开的文件。 – sc100

+0

@ sc100我已通过修改代码添加了答案。请看一看。如果有效,通过接受帮助他人来验证。 –