gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:36:25 26 4
gpt4 key购买 nike

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 循环写入文件,但是当我运行代码时,程序不会循环超过一次。出现一条错误消息,指出程序停止工作,并且创建的文本文档中没有任何内容。我尝试了该网站上的一些建议,但编码似乎还有其他问题。没有错误或警告消息。有人可以告诉我我做错了什么吗?

最佳答案

您的结构体定义为 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);
}

关于c - C 编程中使用 for 循环写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36106706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com