// Demonstration of string steams and strstreams #include #include //for strstreams #include /* For stringstreams, NOT */ #include using namespace std; /* A couple of useful functions from chapter 11 of Horstmann CCC 2nd Edn. Page 454. for converting doubles to strings and vice versa, using a technique from chapter 10. Please copy, use, and say where these came from... Also modify to convert strings to and from int, float, long, ... data. */ double string_to_double(string s); string double_to_string(double x); main() { //An istrstream is useful for extracting data from a character array char* data = "January 23, 1999"; istrstream instr(data); string month; int day; string comma; int year; instr >> month >> day >> comma >> year; cout << month << ":" << day <<":"<< comma <<":" << year<< endl; // Extracting data from a C++ string istringstream instr2(string("February 24, 2004")); instr2 >> month >> day >> comma >> year; cout << month << ":" << day <<":"<< comma <<":" << year<< endl; //This shows making doubles into strings and vice versa cout << "1.2345 = " << double_to_string(1.2345) << endl ; cout << "1.0+1.0 = " << string_to_double("1.0")+string_to_double("1.0") << endl ; return 0; } double string_to_double(string s) { istringstream instr(s); // OR istrstream instr(s.c_str()); /*notice the c_str()*/ double x; instr >>x; return x; } string double_to_string(double x) { ostringstream outstr; outstr << x; return outstr.str(); }