hello sir , i wanted to know about this stringstream operator how it is working.
string reverseWords(string s) {
istringstream is(s);
string tmp;
is >> s;
cout <<s<<endl;
while(is >> tmp) s = tmp + " " + s;
if(s[0] == ’ ') s = “”;
return s;
}
Information about stringstream
https://ide.codingblocks.com/s/285691 i tried but it si not running please see the error i am confused
https://ide.codingblocks.com/s/285691 i tried but it is not running please see the error i am confused
you did’nt include the header file i.e. #include < sstream >
#include <iostream>
#include <sstream>
using namespace std;
string reverseWords(string s) {
istringstream is(s);
string tmp;
is >> s;
while (is >> tmp) s = tmp + " " + s;
if (s[0] == ' ') s = " ";
return s;
}
int main()
{
string s;
getline(cin,s);
cout << reverseWords(s) << endl;
return 0;
}
this code works fine , let me explain how stringstream works , see to understand this you have to compare this with cin and cout , what stringstream do is it associates a string with a stream allowing you to read from the string as if it were a stream,like a continous flow of input (like cin ).when you enter a some words in the input you are passing a stream and what cin does is take words (space seperated) and adds the value to the corresponding variable using >> ,similarly here, we are creating an object is ,which acts like cin (as cin is an object of iostream class) it reads words until there is no word to read ,
if s is a sentence say , “How are you doing?” then is>>s will assign first word to s, i,e how , and the pointer will shift to next word , now we will enter in while loop which runs till end of input(similarly like while(cin>>s) ) tmp will contain “are” ,so s=are+" "+how
, again pointer will shift to next word , is>>tmp will assign “you” to temp and now s=you+" "+"are how"
, and finally we will have tmp as “doing?” making s as “doing? you are How”
this must be confusing if you don’t have much idea on streams and i/o using cin and cout ,
refer this to get more idea on stringstream
In case of any doubt feel free to ask
Mark your doubt as RESOLVED if you got the answer
yes resolved thanks sir !!!
sir one last thing can we do while(cin>>s) instead of while(is>>temp) will it work same?
ok sir got it now !!!