Reverse alternate words in a string

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
Get word from sentence.
If word number is even
    Reverse it and output result
else
    Output world
Would using the function substr do the trick? Do I need to loop it.
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
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.