Search code examples
c++streamoperator-overloadingifstreamsyntactic-sugar

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?


Solution

  • 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.