Course List: http://www.c-jump.com/bcc/
Today:
Using memory buffer as stream of bytes
Key areas:
data -> text conversion
text -> data conversion
A stringstream reads/writes from/to a string rather than a file or a keyboard/screen. For example,
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; // if possible, convert characters in s to floating-point value double str_to_double(string s) { istringstream is(s); // // make a stream so that we can read from s double d; is >> d; if ( !is ) throw runtime_error( "double format error" ); return d; }//str_to_double // testing void doit() { double d1 = str_to_double( "12.4" ); double d2 = str_to_double( "1.34e-3" ); double d3 = str_to_double( "twelve point three" ); // error }//doit int main() { try { doit(); } catch ( runtime_error err ) { cerr << err.what() << '\n'; } system( "pause" ); return 0; }//main()
String streams are very useful for
formatting a string that contains structured data, e.g. HTML, XML, or SQL:
SELECT product_code, description, price FROM table_products WHERE product_code = 'BOOK' AND price < 60.50
extracting typed objects out of a string:
int string_2_int( string str ) { int value; istringstream iss( str ); iss >> value; return value; }
#include <cassert>
#include <string>
#include <sstream>
int main()
{
const double PI = 3.1415926;
double value;
std::stringstream buffer; // text buffer
buffer.precision( 8 ); // increase default precision (*)
buffer << PI; // formatted output
buffer >> value; // formatted input
assert( PI == value );
std::string text;
text = buffer.str( ); // returns std::string
buffer.str( "" ); // clear buffer
return 0;
}
(*) try commenting out precision change and see what happens
#include <cassert> #include <iostream> #include <sstream> using namespace std; int main() { stringstream buffer; int onechar; // because char cannot represent EOF cout << "Enter some text: "; while ( ( onechar = cin.get() ) != EOF ) { if ( onechar == '\n' ) { break; // exit loop at the end of the line } else if ( isalpha( onechar ) ) { buffer << "alpha: " << char( onechar ) << '\t' << onechar <<'\n'; } else if ( isdigit( onechar ) ) { buffer << "digit: " << char( onechar ) << '\t' << onechar <<'\n'; } else { buffer << "other: " << char( onechar ) << '\t' << onechar <<'\n'; } } cout << buffer.str() << '\n'; // str() returns string return 0; }
This handout is using material from Programming -- Principles and Practice Using C++
About the author: Bjarne Stroustrup's homepage