Reverse string

Nov 7, 2018 at 7:18pm
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;
}
Nov 7, 2018 at 7:26pm
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.

Nov 11, 2018 at 6:23pm
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 Nov 11, 2018 at 8:14pm
Nov 11, 2018 at 8:17pm
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/
Nov 11, 2018 at 8:37pm
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 << " ";
    }
}
Nov 12, 2018 at 12:03pm
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.