Reversing alternate (even) words in a string

I am trying to reverse every alternate word in a sentence for example:

[INPUT]
The black cat sat up on the orange mat!
[OUTPUT]
The kcalb cat tas up no the egnaro mat!

I'm trying to use substring to help solve my problem for accounting the spaces but when trying to do so I'm getting an indefinite loop.


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
30
31
32
33
34
35
#include<iostream> 
#include<string>

using namespace std;

int main()
{
	string text, save, final_output, reverse_word;
	int word_count(0);
	int pos(0);
	int length(0);
	cout << "Enter a sentence: ";
	getline(cin, text);
	for (int i = 0; i < text.size(); i++)
	{
		length = pos - 1;
		pos = text.find(' ', pos);
		save = text.substr(i, length);
		word_count++;
	
		if (word_count % 2 == 0)
		{
			 reverse_word += string(save.rbegin(),save.rend());
		}
		else
		{
			reverse_word += save;
		}
		final_output += reverse_word;
		i = pos;
	}
	cout << final_output;
	system("PAUSE");
	return 0;
}
Do you mean an infinite loop?
MiiNiPaa gave some suggestions for the word reversing problem in this thread that might help.

http://www.cplusplus.com/forum/beginner/149338/
Topic archived. No new replies allowed.