-1

I'm writing a function to reverse words in a string. My idea is to split a string by ' ', push the words into a stack and pop them out to print the string with their words reversed.

But , I am not able to split the string using stringstream class.

My code is as follows:

#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<string>
#include<bits/stdc++.h>

using namespace std;


void reverse_words(string s){

    stack <string> stack_words;

    string popped_element;

    string result = "";

    stringstream split(s);

    string token;

    while(getline(split,token,' ')){

        cout<<"pushed "<<token;
        stack_words.push(token);
    }

    while(!stack_words.empty()){

        popped_element = stack_words.top();
        stack_words.pop();

        result.append(" ");
        result.append(popped_element);

    }

    cout<<result;

}



int main(){

    string s,res;

    cout<<"\n Enter a string :";
    cin>>s;

    reverse_words(s);

}


For example , when I input ' Hello World' , only 'Hello' is pushed into the stack whereas I need both 'Hello' and 'World' present in the stack.

Does anyone know what is wrong with my code ?

AnonymousMe
  • 509
  • 1
  • 5
  • 18
  • 1
    Cin stops reading after space, so s is only Hello – DevUt Dec 22 '20 at 18:05
  • Thanks , I understand the issue now . – AnonymousMe Dec 22 '20 at 18:10
  • 1
    @DevUt — stream extractors (`operator>>`) stop reading at white space. Other input operations, including `getline`, do not. – Pete Becker Dec 22 '20 at 18:10
  • Unrelated: Read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and break free of the [cargo cult](https://en.wikipedia.org/wiki/Cargo_cult_programming). – user4581301 Dec 22 '20 at 18:48

2 Answers2

3

In your case, the stream extractor (operator >>) stops reading after the space in Hello world so s="Hello". To solve this use getline(cin,s);

Edidted to include more detail as told by @Pete Becker

DevUt
  • 1,280
  • 11
  • 24
0

How about this?

#include <bits/stdc++.h>
#include <iostream>

using namespace std;

void reverseWords(string s)
{
    vector<string> tmp;

    string str = "";

    for (int i = 0; i < s.length(); i++) 
    {
        if (s[i] == ' ') 
        {
            tmp.push_back(str);
            str = "";
        }
        else
            str += s[i];
    }
    tmp.push_back(str);
    int i;
    for (i = tmp.size() - 1; i > 0; i--)
        cout << tmp[i] << " ";

    cout << tmp[0] << endl;
}

int main()
{
    string s;
    getline(cin,s);
    reverseWords(s);
    return 0;
}
secdet
  • 300
  • 1
  • 2
  • 11