user12008861
user12008861

Reputation: 1

using std::get_temporary_buffer to read data from file

I have this structure

struct myStruct {
    int i,j;
    double x,y,z,f;
    myStruct(int i_, int j_, double x_, double y_, double z_, double f_):
        i(i_),j(j_),x(x_),y(y_),z(z_),f(f_){}
    }
};

and I would like to read data from text file (with 5 columns) and put them into a vector of strcuture myStruct. I would like to separate the reading from text file and the inserts into the vector. For reading I have to use a temporary buffer in memory, can I use get_temporary_buffer and how can I do it please?

Upvotes: 0

Views: 118

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117308

std::get_temporary_buffer was deprecated in C++17 and will (most probably) be removed in C++20, so I wouldn't use that in any new programs, but you can easily add your own operators for formatted streaming.

#include <ios>
#include <iostream>
#include <sstream>
#include <string>

struct myStruct {
    int i, j;
    double x, y, z, f;

    myStruct(int i_, int j_, double x_, double y_, double z_, double f_) :
        i(i_), j(j_), x(x_), y(y_), z(z_), f(f_) {}

    myStruct() : // default constructor
        myStruct(0, 0, 0., 0., 0., 0.) // delegating
    {}

    /* if you make your member variables private, you'll need to make the
     * streaming functions friends, like this:
    friend std::istream& operator>>(std::istream&, myStruct&);
    friend std::ostream& operator<<(std::ostream&, const myStruct&);
    */
};

std::istream& operator>>(std::istream& is, myStruct& m) {
    std::string line;
    // read one line from the stream
    if(std::getline(is, line)) {
        // put the line in an istringstream for extracting values
        std::istringstream ss(line);
        if(!(ss >> m.i >> m.j >> m.x >> m.y >> m.z >> m.f)) {
            // if extraction failed, set the failbit on the stream
            is.setstate(std::ios::failbit);
        }
    }
    return is;
}

std::ostream& operator<<(std::ostream& os, const myStruct& m) {
    return os << m.i << ' ' << m.j << ' ' << m.x << ' ' << m.y << ' ' << m.z << ' '
              << m.f << "\n";
}

int main() {
    // using a simulated file (a_file) opened for reading:
    std::istringstream a_file(
        "1 2 3.1 4.2 5.3 6.4\n"
        "2 3 4.1 5.2 6.3 7.4\n"
        "3 4 5.1 6.2\n"); // the last line will fail to be extracted since it
                          // contains too few values

    myStruct tmp;
    // Read until eofbit, failbit or badbit is set on the stream.
    // The stream object will be "true" in a boolean context (like the
    // while(<condition>)) if it's in a good state.
    while(a_file >> tmp) {
        // the stream "a_file" is in a good state so extraction succeeded
        std::cout << tmp;
    }
    std::cout << "goodbye\n";
}

Upvotes: 1

Related Questions