gpt4 book ai didi

c - 如何添加不断询问用户输入并将所有输入保存到文件

转载 作者:太空宇宙 更新时间:2023-11-04 03:12:13 24 4
gpt4 key购买 nike

我的代码有一个问题:每当我想添加一个新病人时,就会发生一些可疑的事情。如果我一次写一个病人然后退出登记,我输入的病人就会在文件中找到。但是,如果我一次写入多个患者,则只会保存最后一个患者的输入,其余的则不会保存。我相信这与我的阵列有关,但我无法确定。有什么建议吗?

代码如下:

    FILE *patientfile;
char answer;

patientfile= fopen("test.txt", "a");
if (!patientfile)
{
printf(" Failed to open file.\n");
}

do
{
int i=0;

printf(" Enter details of patient %d\n\n", i+1);

printf(" Patients first name: ");
scanf("%s",arr_patient[i].fname);
printf(" Last name: ");
scanf("%s",arr_patient[i].lname);
printf(" Personnummer: ");
scanf("%d", &arr_patient[i].birthdate);
printf(" Bildref: ");
scanf("%d", &arr_patient[i].bildref);

printf(" Do you want to add someone else?: (y/n):");
scanf(" %c",&answer);

i++;

}while(answer != 'n');

int i = 0;

fprintf(patientfile," %s\t%s \n ", arr_patient[i].fnamn,arr_patient[i].lnamn);
fprintf(patientfile," %d \n",arr_patient[i].birthdate);
fprintf(patientfile," %d \n",arr_patient[i].bildref);



fclose(patientfile);

}

编辑:问题已解决!谢谢大家!

最佳答案

这是应该做的(我在代码中嵌入了关于问题的注释)

char answer;
// NOTE: this must be outside the loop
int i=0;
do
{
printf(" Enter details of patient %d\n\n", i+1);

printf(" Patients first name: ");
scanf("%s",arr_patient[i].fname);
printf(" Last name: ");
scanf("%s",arr_patient[i].lname);
printf(" Personnummer: ");
scanf("%d", &arr_patient[i].birthdate);
printf(" Bildref: ");
scanf("%d", &arr_patient[i].bildref);

printf(" Do you want to add someone else?: (y/n):");
scanf(" %c",&answer);

i++;

}while(answer != 'n');

FILE *patientfile = fopen("test.txt", "a");
if (!patientfile) printf(" Failed to open file.\n");

// NOTE: You need to loop over the array and write all the patients to the file
for(int j=0; j<i; j++)
{
fprintf(patientfile," %s\t%s \n ", arr_patient[j].fnamn,arr_patient[j].lnamn);
fprintf(patientfile," %d \n",arr_patient[j].birthdate);
fprintf(patientfile," %d \n",arr_patient[j].bildref);
}
fclose(patientfile);

但实际上您并不需要数组。您可以像这样直接将患者写入文件:

FILE *patientfile = fopen("test.txt", "a");
if (!patientfile) printf(" Failed to open file.\n");
char answer;
int i=0;
do
{
// change patient_struct to your structure name
patient_struct patient;
printf(" Enter details of patient %d\n\n", i+1);

printf(" Patients first name: ");
scanf("%s",patient.fname);
printf(" Last name: ");
scanf("%s",patient.lname);
printf(" Personnummer: ");
scanf("%d", &patient.birthdate);
printf(" Bildref: ");
scanf("%d", &patient.bildref);

fprintf(patientfile," %s\t%s \n ", patient.fnamn, patient.lnamn);
fprintf(patientfile," %d \n", patient.birthdate);
fprintf(patientfile," %d \n", patient.bildref);

printf(" Do you want to add someone else?: (y/n):");
scanf(" %c",&answer);

i++;

}while(answer != 'n');
fclose(patientfile);

关于c - 如何添加不断询问用户输入并将所有输入保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55263404/

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