Please explain why the output is like this

Asked 2 years ago, Updated 2 years ago, 30 views

int main() { FILE *fp; char str[20];

fp = fopen("a.txt", "a+");
if (fp == NULL)
{
    printf("Failed to create file".\n");
    return 1;
}
while (1)
{
    printf ("Fruit name: ");
    scanf("%s", str);
    if(strcmp(str,"end")==0)
    {
        break;
    }
    else if (strcmp(str, "list") == 0)
    {
        fseek(fp, 0, SEEK_SET);
        while (1)
        {
            fgets(str, sizeof(str), fp);
            if (feof(fp))break;
            printf("%s", str);
        }
    }
    else
    {
        fprintf(fp, "%s\n", str);
    }

}
fclose(fp);

return 0;

}

If you run this code,

Why is this happening? I'm supposed to use only one fruit name, but I purposely used two or three, but why are the fruit names coming out twice and three times? Please explain the principle

c

2022-09-22 18:55

2 Answers

Processing of open characters is a problem due to buffer problems when receiving input with scanf.

This means that the buffer must be empty.

The reason and solution are summarized in the link below.

http://ddoddofather.tistory.com/entry/C%EC%96%B8%EC%96%B4-%EC%9E%85%EB%A0%A5%EB%B2%84%ED%8D%BC%EB%A5%BC-%EB%B9%84%EC%9A%B0%EB%8A%94-%ED%95%A8%EC%88%98


2022-09-22 18:55

If you empty the buffer above, you can refer to the getchar() link You're going to have to write scanf as follows.

scanf("%[^\n]", str);


2022-09-22 18:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.