14.5 C++14: Reading and Writing Quoted Text

Many text files contain quoted text, such as "C++ How to Program". For example, in files representing HTML5 web pages, attribute values are enclosed in quotes. If you’re building a web browser to display the contents of such a web page, you must be able to read those quoted strings and remove the quotes.

Suppose you need to read from a text file, as you did in Fig. 14.5, but with each account’s data formatted as follows:


100 "Janie Jones" 24.98

Recall that the stream extraction operator >> treats white space as a delimiter. So, if we read the preceding data using the expression in line 30 of Fig. 14.5


inClientFile >> account >> name >> balance

the first stream extraction reads 100 into the int variable account and the second reads only "Janie into the string variable name (the opening double quote would be part of the string in name). The third stream extraction fails while attempting to read a value for the double variable balance, because the next token (i.e., piece of data) in the input stream— Jones"—is not a double.

Reading Quoted Text

C++14’s new stream manipulator—quoted (header <iomanip>)—enables a program to read quoted text from a stream, including any white space characters in the quoted text, and discards the double quote delimiters. For example, if we read the preceding data using the expression


inClientFile >> account >> quoted(name) >> balance

the first stream extraction reads 100 into account, the second reads Janie Jones as one string and stores it in name without the double-quote delimiters, and the third stream extraction reads 24.98 into balance. If the quoted data contains " escape sequences, each is read and stored in the string as the escape sequence "—not as ".

Writing Quoted Text

Similarly, you can write quoted text to a stream. For example, if name contains Janie Jones, the statement


outputStream << quoted(name);

writes to the text-based outputStream


"Janie Jones"
..................Content has been hidden....................

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