Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to convert a string to an istream

Status
Not open for further replies.

deb9

Programmer
Sep 21, 2005
8
0
0
US
Hi,

I have a code that reads some text from cin and parses it with a function whose header looks like

read(istream &in)

I would like to add a GUI with a textbox so that the user types in the textbox rather than to cin. I still would like to use read(istream &in) though. How do I convert the string typed in the textbox into an istream that can be parsed by read? (Is this even possible?)

Thanks

debbie
 
Use class istrstream from <strdtream>, it is istream descendant (public inheritance); for example:
Code:
#include <strstream>
...
void f(istream& in)
{
   string s;
   in >> s; // now s == "Hello" (see later)
   ...
}
...
  char text[80]; // text from controls etc
  ... // suppose we have "Hello world" string in text array
  istrstream s(text);
  f(s);
 
ArkM, is there a reason you would recommend the deprecated istrstream over the generally preferred istringstream from <sstream>?
Code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

void read(istream& in)
{
   string s;
   while (in >> s)
       cout << s << endl;
}

int main()
{
    istringstream istr("Hello World Goodbye.");
    read(istr);
}
 
Sorry, no reason...
Of course, <sstream>. The same effect + C++ Standard compliance.
Thank you, uolj.
 
Thanks! That was very helpful

deb
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top