在c编程中使用for循环写入文件

时间:2016-03-19 20:22:24

标签: c

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 个答案:

答案 0 :(得分: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);
}