2016-03-19 52 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); 
}