19.12. String Stream Processing

In addition to standard stream I/O and file stream I/O, C++ stream I/O includes capabilities for inputting from, and outputting to, strings in memory. These capabilities often are referred to as in-memory I/O or string stream processing.

Input from a string is supported by class istringstream. Output to a string is supported by class ostringstream. The class names istringstream and ostringstream are actually aliases defined by the typedefs

typedef basic_istringstream< char > istringstream;
typedef basic_ostringstream< char > ostringstream;

Class templates basic_istringstream and basic_ostringstream provide the same functionality as classes istream and ostream plus other member functions specific to in-memory formatting. Programs that use in-memory formatting must include the <sstream> and <iostream> headers.


Image Error-Prevention Tip 19.1

One application of these techniques is data validation. A program can read an entire line at a time from the input stream into a string. Next, a validation routine can scrutinize the contents of the string and correct (or repair) the data, if necessary. Then the program can proceed to input from the string, knowing that the input data is in the proper format.



Image Error-Prevention Tip 19.2

To assist with data validation, C++11 provides powerful regular-expression capabilities. For example, if a program requires a user to enter a U.S. format telephone number (e.g., (800) 555-1212), you can use a regular-expression pattern to confirm that the user’s input matches the expected format. Many websites provide regular expressions for validating email addresses, URLs, phone numbers, addresses and other popular kinds of data. We introduce regular expressions and provide several examples in Chapter 24.



Image Software Engineering Observation 19.1

Outputting to a string is a nice way to take advantage of the powerful output formatting capabilities of C++ streams. Data can be prepared in a string to mimic the edited screen format. That string could be written to a disk file to preserve the screen image.


Image

An ostringstream object uses a string object to store the output data. The str member function of class ostringstream returns a copy of that string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.132.33