Reverse string

closed account (EAp4z8AR)
I need to reverse a string input wether it is one word or a sentence, but if it is a sentence I need to keep the order of the words in the sentence the same just change the order of the letters in the word. I have gotten it to work to the point that the sentence and words are both being reversed. Any ideas of how to fix it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  void reverse(string input);

int main()
{
    string statement;
    cout << "Please enter a string with spaces:\n";
    getline(cin, statement);
    reverse(statement);
}

void reverse(string input)
{
    input=string(input.rbegin(),input.rend());
    cout << input;
}
If you want to maintain the order of the words and just change the order of the characters in the words then it would probably be easiest if you used a stringstream to split the sentence into words, reverse the words and re-assemble the sentence.

closed account (EAp4z8AR)
How would I use split stream because from the sources I viewed they don't work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void reverse(string input)
{
    do
    {
        istringstream ss (input);
        
        string word;
        ss >> word;
        word=string(word.rbegin(),word.rend());
        cout << word;
    }
    while
    {
        (ss);
    }
}
Last edited on
closed account (EAp4z8AR)
The debugger says there is an issue with line 14. But it works for the source that I found.

https://www.geeksforgeeks.org/split-a-sentence-into-words-in-cpp/
closed account (EAp4z8AR)
This is the final product.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void reverse(string input);

int main()
{
    string statement;
    cout << "Please enter a string with spaces:\n";
    getline(cin, statement);
    reverse(statement);
    return 0;
}

void reverse(string input)
{
    stringstream ss(input);
    string word;
    while (getline(ss, word, ' '))
    {
        word=string(word.rbegin(),word.rend());
        cout << word << " ";
    }
}
As you said you want to maintain the order of the words and just change the order of the characters in the words then it is very easy if you used a string stream to split the sentence into words, and reverse the words and re-assemble the sentence.
Topic archived. No new replies allowed.