A program which inverts words

Hi! I want to make a program that flips the words user types. If I type "Hi how are you?" I want the program to return "iH woh era ?uoy". So far I've done this, but this code inverts the whole sentence. Could someone help me out please? :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstring>
using namespace std;

int main ()
{
    string sentence;
    cout << "Type a sentence: ";
    getline(cin, sentence);
    
    int L = sentence.length();
    
    for(int i=L-1; i>=0; i--)
    cout << sentence[i];
    
    system("pause");
    return 0;
}
Last edited on
I won't give you the code as it's best that you figure things our on your own, but here's an idea of how it might work. You know how to print a string in reverse, so all you need to do now is isolate the individual words in the sentence.

Store the position of the beginning of the string at the start of a word, then step through the string until you find a space, at this point take the character before the space as your end position of your word. You know the start and end point of a word now, so print it in reverse. Now set the position after the space to your new start position and continue to step through looking for the next space. Do this in a loop until you reach the end of the string.
You want to flip individual words in the sentence, but not the order of the words in the sentence itself. Your algorithm is correct for the words, but you are applying it to the whole sentence.

Try using a std::istringstream to break the sentence into words. Use a function to do the flipping. Pseudocode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
main:
  string sentence;
  cout << "Type a sentence: ";
  getline( cin, sentence );

  istringstream words( sentence );
  string word;
  while (words >> word):
    flip_word( word );

  // Don't use system("pause")
  cout << "Press ENTER to quit.";
  cin.ignore( 1000, '\n' );
  return 0;

Also, line 2 should read #include <string> .
Don't forget to #include <sstream> for the stringstreams too.

Hope this helps.
I didn't even know you could use a stringstream like that, so that it automatically extracts words, cool.
Last edited on
So my idea is something like this:

1
2
3
4
5
6
for(int j=0; j<L; j++)           //Going through whole string
    if(word[j]==" ")               //If space found
    word[j]=newword[j];     //Remember the space position
    for(int i=0; i<j; i++)       //Going through first word only
                                         //Flip the word
                                         //Continue from newword[j+1]  

This won't work as I have not figured it out completely, but is this good thinking?
Last edited on
Topic archived. No new replies allowed.