#include<iostream>
#include<string>
usingnamespace std;
int main()
{
string sentence, reversed_sentence, buffer;
int no_words(0);
cout << "Enter a sentence: ";
cin >> sentence;
for (int c = sentence.size(); c >= 0; c--)
{
if (sentence[c] >= 'a' && sentence[c] <= 'z'
||
sentence[c] >= 'A' && sentence[c] <= 'Z')
{
buffer += sentence[c];
}
if (sentence[c] == ' ')
{
no_words++;
reversed_sentence = string(buffer.rbegin(),buffer.rend());
buffer = ' ';
}
}
cout << reversed_sentence << endl << endl;
system("PAUSE");
return 0;
}
Basically, its working from right to left, one character at a time, if its a character its added to the buffer, if it finds a space it increments no_words and reverses the word peg to gep in this case (ignoring that the fact that I need to only reverse the alternate (even) words).
#include<iostream>
#include<string>
usingnamespace 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;
}