← Patterns

Validate multiple reads

12345678910111213141516171819#include <sstream> #include <string> int main() { std::istringstream stream{"Chief Executive Officer\n" "John Smith\n" "32"}; std::string position; std::string first_name; std::string family_name; int age; if (std::getline(stream, position) && stream >> first_name >> family_name >> age) { // Use values } }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++98 or newer.

Intent

Ensure that multiple stream reads are successful before using the extracted values.

Description

We create a std::istringstream as 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 && operator 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 successful.

If you are reading values on multiple lines, consider reading from the stream line-by-line and then parsing each line.

Contributors

  • Joseph Mansfield

Last Updated

27 August 2018

Source

Fork this pattern on GitHub

Share