How to write and read struct from a text file in C++

1 Answer

0 votes
#include <iostream>
#include <fstream>

struct Example {
    float x, y;
};

int main(void)
{
    Example ex = { 3.14f, 17.25f };

    // write

    std::ofstream ofs;
    ofs.open("data.txt");
    if (!ofs) {
        std::cout << "error opening file";
        exit(1);
    }

    ofs << ex.x << " " << ex.y;

    ofs.close();

    // read

    ex.x = 0;
    ex.y = 0;

    std::ifstream ifs;
    ifs.open("data.txt");
    if ( !ifs ) {
        std::cout << "error opening file";
        exit(1);
    }
        
    ifs >> ex.x >> ex.y;

    ifs.close();

    std::cout << ex.x << ", " << ex.y << "\n";
}


// data.txt
// --------
// 3.14 17.25


/*
run:

3.14, 17.25

*/



 



answered Jan 29, 2023 by avibootz
edited Jan 29, 2023 by avibootz

Related questions

1 answer 109 views
109 views asked Jan 29, 2023 by avibootz
1 answer 168 views
168 views asked Dec 30, 2020 by avibootz
1 answer 99 views
99 views asked Jan 29, 2023 by avibootz
1 answer 190 views
1 answer 152 views
...