60 likes | 76 Views
C++ stringstream. The I/O problem. Accepting text input from the user is one of the most difficult programming problems in any language Most I/O libraries are capable of reading in all sorts of data But they are less good at dealing with unexpected data
E N D
The I/O problem • Accepting text input from the user is one of the most difficult programming problems in any language • Most I/O libraries are capable of reading in all sorts of data • But they are less good at dealing with unexpected data • E.g. character data entered where a number is expected • E.g. Orphan new line characters in input
Using strings • The standard solution to the problem of dealing with unexpected user input is to read in data one full line at a time into a string • e.g. by using getline() functions • Problem is that extracting meaningful data from the string is hard • We lose all the advantages of the input routines provided by C++ stream types
stringstream • In C programming we are able to break up strings using sscanf(), which offers all the features of scanf(), but operates on strings • In C++ the stringstream class provides an interface to manipulate strings as if they were streams • We can use all the usual stream operators on objects of stringstream type • >>, <<, getline, etc.
stringstream • The stringstream class can be used • to extract data from a string • to build up a string of data using the notation for writing to a file
stringstream #include <sstream> int val; stringstream s; s << “120 42 277 6 5 200” for (int i = 0; i < 6; i++ ) { s >> val; cout << val << endl; }