Print each word in a separate line from an input string

c++charprintfscanfstring

I'm having trouble printing each word in a separate line from an input string in C. The question from the assignment I'm doing states:

Take a sentence as input and print its words in separate lines.

My Code:

#include<stdio.h>

int main()
{
   int i;
   char s[100];

   scanf("%s", s);

   for(i=0; s[i]!='\0'; i++)
   {
      printf("%c", s[i]);

      if(s[i]==' ')
      {
         printf("\n");
      }
   }
}

Any help would be appreciated.

Best Solution

In your code,

  printf("%s", s[i]); 

is wrong. Change it to

 printf("%c", s[i]); 

as, you're trying to print a char value. The conversion specifier for a char is %c.

Note: Always remember, using wrong conversion specifier will lead to undefined behaviour.

Also, while scan()-ing with %s, you cannot read the whole space-delimited input as a single string. From the man page,

%s

Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

You need to use fgets() to do the job.

That said,

  1. Indent your code properly, make it human-readable.
  2. Chnage scanf("%s", s); to scanf("99%s", s); to avoid possible buffer overflow by putting longer input string than 99 chars.
  3. the proper signature for main() is int main(void).