Reverse alternate words in a string

Nov 23, 2014 at 1:57pm
How do reverse every alternate words in a string that I read into my program:

e.g. The mouse was caught in a clothes peg.
reversed (including the full stop)
The esoum was thguac in a clothes gep.
I could program it to reverse the whole sentence. But no clue how to reverse certain words such as every even word.
Do I need a function and/or loop to solve this?

#include<iostream> // allow input and output
#include<string> // allow for larger entries of characters
using namespace std;

int main()
{

string sentence, reversed_sentence;
int no_words(0);
cout << "Enter a sentence: ";
getline(cin, sentence);
for (int c=0; c <= sentence.size(); c++)
{

}
system("PAUSE");
return 0;
}
Last edited on Nov 23, 2014 at 2:00pm
Nov 23, 2014 at 2:02pm
Get word from sentence.
If word number is even
    Reverse it and output result
else
    Output world
Nov 23, 2014 at 3:24pm
Would using the function substr do the trick? Do I need to loop it.
Nov 23, 2014 at 4:08pm
Would using the function substr do the trick?
Sure you can, but there is a tool to do exactly that:
http://en.cppreference.com/w/cpp/io/basic_istringstream/basic_istringstream
Nov 24, 2014 at 1:50am
multiple ways you could do it, could have it take in strings char at a time, with a flag (bool) to switch it from reverse to straight after every space char. You could apply modulo to signal even or odd and output accordingly.
Topic archived. No new replies allowed.