There is a bit of a trick to it: use a second, inside loop to skip past spaces and another to print words. The outer loop should only terminate if you have reached the end of the string.
while (s[i] != '\0')
{
// skip all spaces
while ((s[i] != '\0') && isspace( s[i] )) ++i;
// print the word
while ((s[i] != '\0') && !isspace( s[i] ))
{
putchar( s[i] );
}
// print the newline after a word
putchar( '\n' );
}
By the way, gets()
is a really, really dangerous function. It should never have been included in the language. You are OK to use it for a homework, but in reality you should use fgets()
.
char s[1000];
fgets( s, sizeof(s), stdin );
The fgets()
function is a bit more fiddly to use than gets()
, but the above snippet will work for you.
Your other option for solving this homework is to use scanf()
to read a word at a time from user input, and print it each time through the loop. I’ll leave that to you to look up. Don’t forget to specify your max string length in your format specifier. For example, a 100 char array would be a maximum 99-character string, so you would use "%99s"
as your format specifier.