2016-03-19 51 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循環寫入文件,但是當我運行代碼時程序不會循環一次以上。出現錯誤消息說程序停止工作,並且沒有任何內容在創建的文本文檔中。我在本網站上嘗試了一些建議,但編碼似乎還有其他問題。沒有錯誤或警告消息。有人能告訴我我做錯了什麼嗎?在c編程中使用for循環寫入文件

+0

'6'的索引是錯誤的。 – BLUEPIXY

+0

'struct customer information [6];'有6個項目,你訪問索引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); 
}