Help Reverse Sentence C Program
Im writing a c program that reverses the words in a sentence,
Example:
you can cage a swallow can't you?
you can't swallow a cage can you?
I have it all working, except the fact that I dont know how to get the words themselves to turn around. Heres my code and an example of the output im getting.
Output Im getting:
Enter a sentence: you can cage a swallow can't you?
Reverse of sentence: uoy t'nac wollaws a egac nac uoy?
My Code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 200 /*Decent number of chars for a sentence*/
int main()
{
/*Initializations*/
char forward_sentence[MAX];
char ch, termch;
int i = 0, j, len = 0;
/*Gets a sentence from the user*/
printf("Enter a sentence: ");
ch = getchar();
/*Loop goes as long as it doesnt hit a terminating char*/
while(i < MAX && ch != '\n' && ch != '.' && ch != '?' && ch != '!')
{
forward_sentence[i] = ch;
i++;
len++;
ch = getchar();
}
/*Sets the terminating characters*/
for(i = 0; i < MAX; i++)
{
if(ch == '.')
termch = '.';
else if(ch == '?')
termch = '?';
else if(ch == '!')
termch = '!';
}
/*Prints out the sentence reversed*/
printf("Reverse of sentence: ");
for(j = len - 1; j >= 0; j--)
{
if(forward_sentence[j] == ' ')
{
}
printf("%c", forward_sentence[j]);
}
printf("%c\n", termch)
return 0;
}