Question: 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 ?

Answer: 
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](https://stackoverflow.com/users/1593860/pete-becker)
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;
}

```