Reverse even words in a string

I'm trying to reverse every even word in a string (not all of it). But I keep getting an empty output.

For example: The mouse was caught in peg.
The esmou was thgauc in gep.

Underlined words (even words)

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
#include<iostream> 
#include<string>
using namespace std;

int main()
{
	string text, result, temp;
	int word_count(0);
	cout << "Enter a sentence: ";
	cin >> text;
	for (int c = 0; c <= text.size(); c++) // character by character (left to right)
	{
		if (text[c] >= 'a' && text[c] <= 'z' // if chracter is a letter
			           ||
		    text[c] >= 'A' && text[c] <= 'Z')
		{
			temp += text[c];	// add to contents of temp
		}
		if (text[c] == ' ')	// if chracter is a space
			{
			word_count++;
			if (word_count % 2 == 0)	// determine even word in a string
				{
					result += string(temp.rbegin(),temp.rend()); // reverse word, 
                                                                                  //concatinate word
				}
			result += temp;			// concatenate non-reversed word
			temp.clear();			// empty temp for next loop
			}
	}
	cout << "New sentence: " <<  result << endl << endl;
	system("PAUSE");
	return 0;
}
For loop is looping over the size of the string (line 11)

line 15 should be:
temp = string(temp.rbegin(),temp.rend());

And finally line 31 should have another one of:

1
2
3
4
5
6
word_count++;
if (word_count % 2 == 0)	// determine even word in a string
{
    temp = string(temp.rbegin(),temp.rend()); // reverse word, 
}
result += temp;


Before the print statement
Last edited on
Topic archived. No new replies allowed.