2

I'm reading the contents of a file through cin and I need to parse the first line

The file looks like:

1 2 3 4
1->3
2->5
...

So basically my first step is to read the first line into a vector of ints.

My approach is the following:

std::string line;
std::vector<int> initial;

std::getline(std::cin, line);
std::istringstream iss(line);
int aux;

while (iss >> aux) {
    initial.push_back(aux);
}

This works, and my vector initial correctly contains the 4 integers of the first line. However I feel like I'm doing a lot of convertions that should be possible to be done in a more direct way.

I am reading the first line into a string and then converting thi string into a stream, I tried directly reading into a stream but compiler complains.

std::istringstream iss();
std::getline(std::cin, iss);

Then I'm looping through the string to obtain the individual ints and saving them in an auxiliary int before being pushed into the vector. I tried directly getting them into the vector, but again not possible (at leaast the way I'm doing it)

while (iss >> initial) {
}

Is there a cleaner way to just get one line from cin consisting of space separated integers directly into a vector of integers?

  • 4
    There's a [vector constructor](http://en.cppreference.com/w/cpp/container/vector/vector) taking a pair of iterators. And you can create [iterators from input streams](https://en.cppreference.com/w/cpp/iterator/istream_iterator). With those it's easy to construct or initialize a vector directly from a stream. – Some programmer dude Dec 10 '18 at 10:59

1 Answers1

3

I'll start from the end:

while (iss >> initial) { ... }

This can easily be made to work using std::back_inserter:

std::vector<int> v;
auto inserter = std::back_inserter(v);

while (iss >> *inserter) { ... }

Frankly, I'd probably leave that as is, but if you absolutely must, you can use std::istream_iterator to initialize the vector directly:

std::vector<int> v (std::istream_iterator<int>{iss}, std::istream_iterator<int>{});

Note: use braces in the constructor of istream_iterator, or use parentheses around at lease one of the constructor's parameters of v to avoid Most-Vexing-Parse

Escape0707
  • 152
  • 1
  • 2
  • 9
Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135