Inverting words in sentence

Hello!
I want to make program which inverts the words in sentence, but not the sentence itself. For example, if I type "I love c plus plus." I program to print "I evol c suls .sulp".

My idea is to go throug the sentence (string) using for loop and look for a space position in it. When found, remebember its position and new for loop now should invert a word and put it in new string. So this would be the end for the first word. Now the first for loop must continue from space position+1 until second space found, an so on...

I have done this, but something's wrong here. I suppose the error is when writing the inverted word into a new char; it writes only spaces. Cannot figure how to solve this out. This is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
using namespace std;

int main() {
    
    char sentence[51];    
    cout << "Type a sentence: ";
    cin.getline(sentence,50);
    int L=strlen(sentence);
    
    int tmp;
    char new_sentence[51];
    
    for(int i=0; i<L; i++) {                                        //Going through string
            if(sentence[i]==' ') {                                  //If space found
                              tmp=i;                                //Remember space position
                              for(int j=tmp-1; j>=0; j--) {         //From space position-1, invert a word
                                      new_sentence[j]=sentence[i];  //and write it into new char
                                      i=tmp;
                                      }
                                      }
                                      }
    
    cout << "Output: " << new_sentence << endl;
    
    system("pause");
    return 0;
}
3 step solution:
1) Break the string up into tokens
2) Inverse the tokens
3) Put the tokens together again to form a new string

You can do 1 and 3 with a stringstream (http://www.cplusplus.com/reference/iostream/stringstream/ ), so basically you just have to do step 2.

Remember when attempting to solve a problem, break the problem up into smaller, solvable units.
Thank you for your help, but is there any other way to do that? I have recently started learning this and this looks not easy... Or am I wrong?
Define easy. I personally think it's pretty simple, but a beginner might have problems. I don't see how else than with the 3 steps I presented you it could be done, though of course the implementation of those steps may vary.
Last edited on
1) Store the words in an array/vector (I would go with vector), in order.
2) Go through each part of the array/vector one by one, and swap the letters in each word.
3) Output.
Topic archived. No new replies allowed.