Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 499
It'sNotALie. Avatar asked Nov 01 '25 02:11

It'sNotALie.


2 Answers

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

arr[*istream_iterator<int>(input)] = something
like image 116
Jonathan Mee Avatar answered Nov 03 '25 18:11

Jonathan Mee


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.

like image 21
Justin Avatar answered Nov 03 '25 18:11

Justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!