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 ?