I'm a beginner at C. It's a text file reading and writing question

Asked 2 years ago, Updated 2 years ago, 31 views

int main(void) { char name[10]; char sex; int age;

FILE *wfp = fopen("friend.txt", "wt");

int i;
for (i = 0; i < 3; i++)
{
    printf("enter name, sex, and age in order : ");
    scanf("%s %c %d", name, &sex, &age);
    getchar();
    fprintf(wfp, "%s %c %d", name, sex, age);
}

FILE *rfp = fopen("friend.txt", "rt");

int ret;

while (1)

{
    ret = fscanf(rfp, "%s %c %d", name, &sex, &age);
    if (ret == EOF);
    break;
    printf("%s %c %d\n", name, sex, age);


}
fclose(wfp,rfp);
return 0;

}

I wonder why only the last input value is always printed three times

c c++

2022-09-22 12:02

2 Answers

at the time of printing Don't just printf("%s%c%d\n", name, sex, age) in the for statement You can get my value by reading the content in fp with the fread function or fscanf.


2022-09-22 12:02

if (ret == EOF); 
break;
This part
if (ret == EOF)
    break;
Change it to.

And I think it's my first time seeing two closed at once with fclose(). Maybe you'd better split it up and do it one by one.


2022-09-22 12:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.