It'sNotALie.
It'sNotALie.

Reputation: 22804

Extract from an ifstream without a temporary variable?

ifstream offers an overload of operator>> to extract values from the next line of the stream. However, I tend to find myself doing this often:

int index;
input >> index;
arr[index] = <something>;

Is there any way to get this data into the [index] without having to create this temporary variable?

Upvotes: 4

Views: 339

Answers (2)

Jonathan Mee
Jonathan Mee

Reputation: 38939

Sure, you can do this by just constructing a temporary istream_iterator for example:

arr[*istream_iterator<int>(input)] = something

Upvotes: 3

Justin
Justin

Reputation: 25337

You can write a function to extract the next value from an istream:

template <typename T> // T must be DefaultConstructible
T read(std::istream& input) {
    T result;
    input >> result;
    return result;
}

Then, you could just write:

arr[read<int>(input)] = <something>;

Although you should probably write

arr.at(read<int>(input)) = <something>;

Because otherwise you open yourself up to a buffer-overflow vulnerability. If the input file had an integer out of range, you'd be writing out of bounds.

Upvotes: 2

Related Questions