/* Lecture code 1.1 * * Examples with a stringstream. This demonstrates how to put data into a stringstream, * as well as how to extract it. */ #include #include // For stringstream #include // Next two lines replace genlib.h using namespace std; /* Function to convert an int to a string. Note that you can easily change * the type of the parameter to get an entirely different function - maybe * converting doubles to strings, for example. Feel free to experiment! */ string IntegerToString(int myInt) { /* Funnel through a stringstream to convert. */ stringstream converter; converter << myInt; /* Use the .str() function to extract the string version. */ return converter.str(); } int main() { /* Create a stream. */ stringstream myStream; /* Insert text data. */ myStream << "137 2.71828 Hello!"; /* Extract numeric and string data. Note that the arrows move the data * out of the stream into the variables. Also note that the order matters * here; reversing the order of extraction results in a fundamentally * different operation. */ int myInt; double myDouble; string myString; myStream >> myInt >> myDouble >> myString; /* Print everything to cout. */ cout << myInt << endl; cout << myDouble << endl; cout << myString << endl; return 0; }