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; ");
	gets(string);
	printf("\n");

	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;
}

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.