2016-03-13 143 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我已通過修改代碼添加了答案。請看一看。如果有效,通過接受幫助他人來驗證。 –