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

时间:2019-03-20 14:39:12

标签: c

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

2 个答案:

答案 0 :(得分:1)

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

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);

答案 1 :(得分:0)

我看到两个问题:

您将每个循环中的i设置为零:

do
{
    int i=0;

因此所有读数都将到达数组索引零。将初始化移出循环:

int i=0;
do
{

因此第一条记录将存储在数组索引0处,第二条记录将存储在数组索引1处,依此类推。

此外,在写入文件时需要循环。当前,您只写一条记录。要写所有记录,请执行以下操作:

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);
}