Reputation: 463
I was using scanf for all my inputs in C. Now I saw other similar questions about scanf()
and they suggested using fgets()
instead of scanf()
. I will do so in the future. However, at the moment this particular part of code with scanf()
never seems to work. I know there is a solution.
My code is:
#define LENGTH 1000
#define WORD 100
int main(){
int i = 0;
char s[WORD][LENGTH];
do {
scanf("%s", s[i]);
i++;
}
while (s[i][strlen(s[i])] != EOF);
printf("%s\n", s);
return 0;
}
There should be something instead of EOF
in the while loop which checks for the end of line. The final result should be an array of words in s[]
and the program should print that array of words without spaces.
Upvotes: 0
Views: 1127
Reputation: 53016
Unfortunately scanf()
does not read the character you need to check for end of line, or at least not using "%s"
as the specifier.
Instead, use the following
char line[100];
if (scanf("%99[^\n]", line) == 1) {
fprintf(stdout, "%s\n", line);
}
This way, it does not stop at white space characters, and it behaves similar to fgets()
, except that it does not read the '\n'
character and that might be a problem if you call it again.
Upvotes: 1