2016-03-19 8 views
-2
struct customer information[6]; 

int count,loop; 

printf("How many records do you want to add?\n"); 
scanf("%d",&loop); 

FILE *ptr; 
ptr = fopen("information.txt","w+"); 
if(!ptr) 
{ 
    printf("file could not be opened\n"); 
    getchar(); 
    return -1; 
} 

for(count=1; count<=10; count++) 
{ 
    printf("Please enter the customer's id number:\n"); 
    scanf("%d",&information[6].idnum); 
    printf("Please enter the customer's first name and last name:\n"); 
    scanf("%s%s",information[6].Fname,information[6].Lname); 
    printf("Please enter the customer's car model type:\n"); 
    scanf("%s",information[6].cartyp); 
    printf("Please enter the customer's license plate number:\n"); 
    scanf("%s",information[6].Licnum); 
    printf("Please enter the customer's car difficulty:\n"); 
    scanf("%s",information[6].Crdffcty); 

fprintf(ptr,"%d\%s\%s\%s\%s\%s\n",information[6].idnum,information[6].Fname,   
information[6].Lname,information[6].cartyp,information[6].Licnum, 
information[6].Crdffcty); 

if(loop==count) 
{ 
    continue; 
} 
} 

fclose(ptr); 
} 

私はforループを使ってファイルに書き込もうとしていますが、コードを実行するとプログラムは1回以上ループしません。プログラムが動作しなくなり、作成されたテキスト文書に何も表示されないというエラーメッセージが表示されます。私はこのサイトの提案のいくつかを試しましたが、それは何か他のコーディングに間違っているようです。エラーや警告メッセージはありません。誰かが私が何をやったのか教えてくれますか?forループを使ったファイルへの書き込み

+0

「6」のインデックスが間違っています。 – BLUEPIXY

+0

'struct customer information [6];'には6つの項目があり、7番目の要素であるインデックス6の要素にアクセスします。 –

答えて

0

構造体に6が定義されていて、インデックス6、つまり7番目の要素にアクセスしようとしています。したがって、最後の要素を必要とすると仮定して、これを行う必要があります。

struct customer information[6]; 

int count,loop; 

printf("How many records do you want to add?\n"); 
scanf("%d",&loop); 

FILE *ptr; 
ptr = fopen("information.txt","w+"); 
if(!ptr) 
{ 
    printf("file could not be opened\n"); 
    getchar(); 
    return -1; 
} 

for(count=1; count<=10; count++) 
{ 
    printf("Please enter the customer's id number:\n"); 
    scanf("%d",&information[5].idnum); 
    printf("Please enter the customer's first name and last name:\n"); 
    scanf("%s%s",information[5].Fname,information[5].Lname); 
    printf("Please enter the customer's car model type:\n"); 
    scanf("%s",information[5].cartyp); 
    printf("Please enter the customer's license plate number:\n"); 
    scanf("%s",information[5].Licnum); 
    printf("Please enter the customer's car difficulty:\n"); 
    scanf("%s",information[5].Crdffcty); 

fprintf(ptr,"%d\%s\%s\%s\%s\%s\n",information[5].idnum,information[5].Fname,   
information[5].Lname,information[6].cartyp,information[5].Licnum, 
information[5].Crdffcty); 

if(loop==count) 
{ 
    continue; 
} 
} 

fclose(ptr); 
}