I am writing a program to reverse the order of words in a string. If there is a sentence,
I love New York!
It should be changed to,
!York New love I
I'm reversing the order of words in a string by storing the last word and then adding space and then storing the second last and so on. But when I print the output it adds a space before printing.
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
string reverse(string s){
vector<string> temp;
string words;
stringstream ss(s);
while (ss>>words)
{
temp.push_back(words);
}
string ans;
for (int i = words.size()-1; i >=0; --i)
{
if (i!=words.size()-1)
{
ans+= " ";
}
ans+=temp[i];
}
return ans;
}
int main(){
string s("My name is Saad Arshad ");
cout<<reverse(s);
return 0;
}
OUTPUT:
" Arshad Saad is name My"
I think the size of words is greater than that of temp thats why its happening but I still need more clarification.