Using instream - > dvalue is of course the right way. But sometimes some right is not always easier or necessarily better.
We could do something like this:
int main() { string s = "grrr,some text,45.4321,54.22134"; double a,b; ASSERT_IS( 2, sscanf( s.c_str(), "%*[^,],%*[^,],%lf,%lf", & a, & b ) ); cout << setprecision(8); SHOW(a); SHOW(b); }
Or maybe something like this, although less effective, might be easier to understand ...
int main() { string s = "grrr,some text,45.4321,54.22134"; vector<string> v; StringSplit( & v, s, "," ); cout << setprecision(8); SHOW(v); SHOW(atof( v[2].c_str())); SHOW(strtod(v[3].c_str(), (char**)NULL)); }
Assuming that:
#define SHOW(X) cout << # X " = " << (X) f << endl /* A quick & easy way to print out vectors... */ template<class TYPE> inline ostream & operator<< ( ostream & theOstream, const vector<TYPE> & theVector ) { theOstream << "Vector [" << theVector.size() << "] {" << (void*)(& theVector) << "}:" << endl; for ( size_t i = 0; i < theVector.size(); i ++ ) theOstream << " [" << i << "]: \"" << theVector[i] << "\"" << endl; return theOstream; } inline void StringSplit( vector<string> * theStringVector, /* Altered/returned value */ const string & theString, const string & theDelimiter ) { UASSERT( theStringVector, !=, (vector<string> *) NULL ); UASSERT( theDelimiter.size(), >, 0 ); size_t start = 0, end = 0; while ( end != string::npos ) { end = theString.find( theDelimiter, start ); // If at end, use length=maxLength. Else use length=end-start. theStringVector -> push_back( theString.substr( start, (end == string::npos) ? string::npos : end - start ) ); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (string::npos - theDelimiter.size()) ) ? string::npos : end + theDelimiter.size() ); } }