// Demonstrate use of "String Streams" // George F. Riley, Georgia Tech, Fall 2009 // The C library "sprintf" (print to a string) is extremely useful // when we have an integer value and we need an ascii string representation // of that integer. For example, we want to create 10 files with names // "file01", "file02" .. "file09". In C programming we would use sprintf // to create the file name into a temporary working "char" buffer. // In C++, we can solve the problem using the stringstream class, in // a more portable and safe way. #include #include #include using namespace std; int main() { for (int i = 0; i < 10; ++i) { ostringstream sstr; sstr << "file" << setw(2) << i; // Writing to the stringstream object sstr does not create a file // but instead writes to a C++ std::string object. string fn = sstr.str(); cout << "File name is " << fn << endl; } // Similarly we can create an input stringstream that is given an existing // string, and that string is used as the data for the stream reads. ostringstream ostr; for (int i = 0; i < 10; ++i) { ostr << i << " "; } istringstream istr(ostr.str()); cout << "istr constructed with " << ostr.str() << endl; for (int i = 0; i < 10; ++i) { int k; // Reading from a istringstream object does not read a file // but instead reads from the initial string. istr >> k; cout << "k is " << k << endl; } }