What's wrong in the below program (What's happening here)? It should break the for loop after the user inserts empty string (presses only ENTER), but in my case it ends in endless for loop. I tried what is in the comments with no success.
#include <stdio.h>
#include <string.h>
struct S {
char str [10];
};
int main(void)
{
int n;
struct S strings [10];
for (n = 0; n < 10; n++) {
# fflush(stdout);
scanf("%s", strings[n].str);
if (strlen(strings[n].str) == 0)
break;
# getchar();
}
printf("done");
return 0;
}
When I replace scanf with gets(strings[n].str); done is never printed. How would you fix it?
This sample solution works. Is there a difference in comparison to my code?
scanf; it's notoriously hard to use, and the way you're using it is susceptible to a buffer overflow. (And never usegets). c-faq.com/stdio/scanfprobs.htmlscanf("%s", strings[n].str);expects at least one non-whitespace character.scanfwill not return until it finds one.getstoo which is used in sample solution by Chuck Allison too.