I am having trouble reversing the words in a sentence. For example "a line of text" should be printed "text of line a". So far I can only print the last word, it is probably obvious but at the minute i just can't see how to do it. Any help would be appreciated. thanks.

/*Write a program that inputs a line of text tokenizes it with strtok and outputs the tokens in reverse.

#include <stdio.h>
#include <string.h>

int main()

	char string[100] ;
	char *tokenPtr;
	char *reverse[10];
	int i;

		printf("Enter a line if text; ");

	tokenPtr = strtok(string, " ");

	/* continue tokenizing sentence until tokenPtr becomes NULL */
	while (tokenPtr != NULL){
		for (i = 0; i < 10; i++){
			reverse[i] = tokenPtr;
		tokenPtr = strtok(NULL, " ");/* get next token */
		for(i = 10; i > 0; i--){
			printf("%s ", reverse[i]);

	return 0;
8 Years
Discussion Span
Last Post by natd

The inner loop should not be there - increment i once each time around the while loop.

The second loop needs to count down from however many words you found.

You MUST NOT use gets(), use fgets() instead. Countless examples of how to use it can be found.


Thanks. Got it sorted now, didn't know about fgets. Haven't got that far yet still a total novice!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.