Topic: string class and istrstream


Author: Edward Diener <70304.2632@CompuServe.COM>
Date: 11 Mar 1995 19:08:37 GMT
Raw View
It seems as if it is much easier to use the sscanf function
rather than the istrstream class when converting a C++ string
class to other values. This is because sscanf takes as a first
parameter a 'const char *' while the istrstream takes as a
constructer a non-const 'char *', among other non-const
constructors. To sonvert a string class instance to another value
using sscanf, you would do something as simple as:
string s;
sscanf(s.c_str(),"etc.". etc.);
but this doesn't work with istrstream since:
string s;
istrstream ss(s.c_str());
ss >> etc.
is illegal because istrstream's constructor is a 'char *' not a
'const char *' . Instead you must do this:
string s;
char * sp = new char[s.length() + 1];
strcpy(sp,s.c_str());
istrstream ss(sp);
ss >> etc.;
string s;
char * sp = new char[s.length() + 1];
strcpy(sp,s.c_str());
istrstream ss(sp);
ss >> etc.;