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
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.
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);
© 2024 OneMinuteCode. All rights reserved.