Reading and writing floats to/from an array to a file

I am trying to store float values that are being used for leaderboard values in a game. I want to read the values in from the file and save them to an array and if a new record is set, write that back to the file.

I have this section reading from the file into my float array:
1
2
3
4
5
6
7
8
9
10
        std::ifstream timeIn;
        timeIn.open("Leaderboard.txt");
        float in;


        for(int i = 0; i < 2; i++)
        {
            timeIn >> in;
            timesTop[i] = in;
        }


And I have this section for the writing the floats to the file:
1
2
3
4
5
6
7
8
9
        std::ofstream timeOut;
        timeOut.open("Leaderboard.txt");

        char timeStr[30];
        for(int i = 0; i < 2; i++)
        {
            sprintf(timeStr, "%.2f ", timesTop[i]);
            timeOut << timeStr;
        }


My issue is that when try to write to the files it writes 0.00 for each float. I'm not sure if it's a writing problem but if I manually change the values of the floats in the file it reads them in correctly.

How do I correctly write an array of floats to a file?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
#include <iomanip>

int main() {
    float top[2];

    std::ifstream in("leaderboard.txt");
    if (!in) {std::cerr << "Can't open leaderboard.txt for reading\n"; return 1;}
    in >> top[0] >> top[1];
    in.close();

    std::ofstream out("leaderboard.txt");
    if (!out) {std::cerr << "Can't open leaderboard.txt for writing\n"; return 1;}
    out << std::fixed << std::setprecision(2)
        << top[0] << '\n' << top[1] << '\n';
    out.close();
}


I'm not sure why your floats are coming out 0.00. Are you sure they are being read in correctly? Maybe the file isn't even opening.
Last edited on
I'm not sure either but your solution worked correctly, could be the sprintf statement, but thanks!
Maybe you didn't close the file after you read it (and timeIn didn't go out of scope and close the file automatically). Then timeOut wouldn't be able to open it (for writing, at least).
Topic archived. No new replies allowed.