/////////////////////////////////////////////////////////////// // strio.cpp - demonstrate strstreams // // // // Jim Fawcett, 24 Mar 96, modified 04 Mar 02 // /////////////////////////////////////////////////////////////// #include // cout, << #include // istrstream(), ostrstream(), <<, >> #include using namespace std; //----< display titles >--------------------------------------- void title(const char *t, char ul = '-', ostream &out = cout) { int len = strlen(t) + 2; string line(len,ul); if(ul == '=') out << "\n " << line; out << "\n " << t << "\n " << line << endl; } //----< begin demonstration >---------------------------------- void main() { /////////////////////////////////////////////////// title("Demonstrating stringstream operations",'='); /////////////////////////////////////////////////// title("reading from string"); ///////////////////////////// istrstream source("15 3.1415927 Now is the hour"); cout << "\n " << source.rdbuf() << endl; title("writing to internal buffer"); //////////////////////////////////// ostrstream destin; // stringstream allocates source.seekg(0); // and manages buffer destin << source.rdbuf() << endl; cout << "\n " << destin.rdbuf(); // title("writing to custom buffer"); ////////////////////////////////// const int bufSize = 50; char custombuf[bufSize]; ostrstream custom(custombuf, bufSize); source.seekg(0); // designer has to ensure custom << source.rdbuf() << ends; // there is no buffer overrun cout << "\n " << custombuf << endl; // -- strstream won't title("parsing input buffer"); ////////////////////////////// int i; double d; char savebuf[bufSize]; source.seekg(0); source >> i >> d; cout << endl; cout << " i = " << i << endl; cout << " d = " << d << endl; int j; // The following operation is dangerous! // extraction writes whole word into buffer, // even if word size is larger than buffer for(j=0; j<4; j++) { source >> savebuf; cout << " savebuf = " << savebuf << endl; } // Here is a saver, though less convenient way // to read strings from a stream title("safe parsing"); ////////////////////// source.clear(); source.seekg(0); string temp; while(source.good()) { char ch = source.get(); if(!isspace(ch)) temp += ch; else if(temp.size() > 0) { cout << "\n " << temp.c_str(); temp = ""; } } if(temp.size() > 0) cout << "\n " << temp.c_str(); cout << "\n\n"; }