Validate multiple reads
This pattern is licensed under the CC0 Public Domain Dedication.
Ensure that multiple stream reads are successful before using the extracted values.
We create a
the example input stream, which contains some values that we wish
to read (lines 6–8). This stream could be replaced by any other
input stream, such as
std::cin or a file stream.
We then create some objects on lines 10–13 into which we will read
values from the stream.
In the condition of the
if statement on lines 15–18, we first perform
an unformatted extraction with
std::getline (line 15)
and then a series of formatted extractions (line 16). The
ensures that the condition is
true only when all extractions
succeed. Short-circuiting also ensures that the second set of
extractions are only attempted if the previous extraction was
If you are reading values on multiple lines, consider reading from the stream line-by-line and then parsing each line.
27 August 2018