Reverse words in string with space not working.

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>

using namespace std;
int main() {
    
    string name;
    string reverse;
    cout<< "Type string  to be reversed : "<<endl;
    getline(cin, name);
    for ( int i=0; i< name.length(); i++){
        reverse = name[i]+ reverse;
    }
    cout<< reverse<<endl;
    
}


I'm trying to reverse a string including spaces. However, my program reverse each string individually. For example, I would like to reverse "This is a coding test". Reverse string : "test coding a is This".
My program does the following :
Type string to be reversed :
"this is a coding test"
"tset gnidoc a si siht"

It does reverse, but it reverses each word in my sentence.
Last edited on
This is one solution that utilizes <sstream> library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string name;
    std::string reverse = "";
    std::cout << "Type string  to be reversed : " << std::endl;
    getline( std::cin , name );

    std::istringstream ss{ name };

    while( ss ) {
        std::string eachWord;
        ss >> eachWord;
        reverse = eachWord + " " + reverse;
    }

    // Remove space at the beginning
    reverse.erase( reverse.begin() );

    std::cout << reverse << std::endl;
}


[EDIT] Forgot to add string library. Surprised that it complied on my machine with no error.
Last edited on
@mpark4656 Could you explain me what does line 11 do? and fro line 12 till 16? I don't understand.
Line 11: Initializes input stringstream variable, ss, with std::string name. Basically, whatever is stored in name is copied to the input stream.
http://www.cplusplus.com/reference/sstream/stringstream/stringstream/

Line 13 - 17: As long as the iostate of ss is "good" (It also means the input stream has not reached End of File). Each string will be extracted from it and stored in eachWord variable until the end of file is reached. Of course, eachWord will be added to reverse variable in the reverse order.
http://www.cplusplus.com/reference/ios/ios/good/

Because of reverse = eachWord + " " + reverse; statement, the reverse variable will have an extra space at the beginning. So, line 20 removes that extra space before printing the result.


General Information on sstream
http://www.cplusplus.com/reference/sstream/stringstream/

Last edited on
I'm trying to reverse a string

No, you are not. A string is a list of characters. You do successfully reverse the list, but that is not what you do want.

You want to take a list of words and reverse that list. The words are initially embedded in one string.

The std::cin is an input stream object. You can read from it. The data comes from "outside".
The ss is an input stream object. You can read from it. The data comes from string 'name'.

The istringstream makes it possible to use formatted input stream operations for reading one word at a time.

You could read word at a time from std::cin too, but then the "end of input" becomes different.


@mpark4656: Do consider this variant:
1
2
3
4
5
6
7
8
std::string eachWord;
while( ss >> eachWord ) {
  if ( reverse.empty() ) {
    reverse = eachWord;
  } else {
    reverse = ...
  }
}

As an alternative, you may also want to have a look at this function:
http://www.cplusplus.com/reference/cstring/strtok/
It splits a string into two pieces based on a specific character, for example the space. In your case you would just have to do it until you reach the end of the string.

To turn the order of the words around, you would have to start printing at the end of the array and reverse to the start of it, this could easily be done by moving the print line in the example to a separate function and using recursion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* slightly modified strtok example */
#include <stdio.h>
#include <string.h>

void reversePrint(char* pch)
{
    if (pch != nullptr)
    {
        reversePrint(strtok (nullptr, " ,.-"));
        printf ("%s\n",pch);
    }
}

int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ,.-");
    reversePrint(pch);
    return 0;
}
Last edited on
closed account (LA48b7Xj)
Here is another solution, I reverse the entire string to start with, then extract words and reverse them back to normal, also the spaces are accounted for so if you wrote a few spaces after a word that would be mirrored.

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
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string input;
    getline(cin, input);
    reverse(input.begin(), input.end());

    stringstream ss {input};
    string word;
    string output;

    for(string::size_type i=0; i<input.size(); ++i)
    {
        if(isspace(input[i]))
            output += ' ';
        else
        {
            ss >> word;
            reverse(word.begin(), word.end());
            output += word;
            i += word.size()-1;
        }
    }

    cout << output << endl;
}
Topic archived. No new replies allowed.