The fact that you don't bother to check the return value from fgets() hurts my brain.
Consider this:
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char buffer[1024];
char *line;
size_t n;
while (NULL != (line = fgets(buffer, sizeof buffer, stdin))) {
/* Skip leading white-space characters. */
while (isspace(*line))
line++;
/* Find the length of the line, excluding newline (CR or LF). */
n = strcspn(line, "\r\n");
/* Skip trailing white-space characters. */
while (n > 0 && isspace(line[n - 1]))
n--;
/* Empty line breaks the loop, ending the program. */
if (n < 1)
break;
/* Trim the line, excluding the trailing white-space and newline. */
line[n] = '\0';
while (1) {
/* Scan backwards, until preceding character is a white-space. */
while (n > 0 && !isspace(line[n - 1]))
n--;
/* Output the string starting there. */
fputs(line + n, stdout);
/* Are we at the start of the line? */
if (n < 1) {
/* Yes, output a newline, and move to next line. */
fputs("\n", stdout);
break;
}
/* We have words before n. Output a space in between. */
fputc(' ', stdout);
/* Scan backwards over the white-spaces. */
while (isspace(line[n - 1]))
n--;
/* Terminate the line there, then continue backwards scan. */
line[n] = '\0';
}
}
return 0;
}
The logic is to first remove leading and trailing whitespace and newline characters from the line.
Scanning backwards from the end of the line, find the start of the last word. It occurs when you are either at the beginning of the line, or the previous character (to the left) is a white-space. You print that string, skip the previous white-space characters, and terminate the string by replacing the first white-space character after a word with '\0'. Repeat until you have printed the first word in the line.