← Patterns

Read a line of values

12345678910111213#include <vector> #include <sstream> #include <iterator> int main() { std::istringstream stream{"4 36 72 8"}; std::vector<int> values; std::copy(std::istream_iterator<int>{stream}, std::istream_iterator<int>{}, std::back_inserter(values)); }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++98 or newer.

Intent

Read a sequence of delimited values from a single line of an input stream into a standard container.

Description

On line 7, we declare a std::istringstream as the input stream, although any other input stream could be used. For user input, you can simply replace stream with std::cin. We have similarly used std::vector as an example container (line 8).

On lines 10–12, we use the std::copy algorithm to copy ints from the input stream to the container. This algorithm takes iterator arguments.

To iterate over the stream, we use the std::istream_iterator<int> type on line 10, which internally uses operator>> to extract ints. The default constructed std::istream_iterator<int> on line 11 denotes the end of the stream.

We use the std::back_inserter helper function on line 12 to create an output iterator that will push_back elements into the given container.

Contributors

  • Joseph Mansfield

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share