Do not use gets
. It's not safe and is deprecated. Use fgets
instead to read an input string stdin
. Now, to print each word in the string backwards, you need to change your while
loop.
#include <stdio.h>
int main(void)
{
int i, j;
char str[100];
printf("Enter String\n");
// fgets reads one less than sizeof(str), i.e., 99
// characters from stdin and stores them in str array.
// it returns when a newline is input which it stores in
// the the array and then appends a terminating null byte
// to mark the end of the string
fgets(str, sizeof str, stdin);
printf("\nString in Reverse Order\n");
i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ' || str[i] == '\n')
{
// the loop condition checks for either the
// start of the string or a whitespace since
// since these two cases demarcate a word from
// other words in the string
for(j = i - 1; j >= 0 && str[j] != ' '; j--)
printf("%c", str[j]);
printf(" ");
}
i++;
}
// output a newline to flush the output
printf("\n");
return 0;
}