简体   繁体   中英

std::ofstream set precision for Floating point format

I need to write float type with 6 digit precision into file. This code does not work correctly as i expected:

int main() {

    std::ofstream ofs("1.txt", std::ofstream::out);
    if (ofs.is_open() == false) {
        std::cerr << "Couldn't open file... 1.txt" << std::endl;
        return -1;
    }

    time_t t_start, t_end;
    time(&t_start);
    sleep(1);
    time(&t_end);
    float elapsed = difftime(t_end, t_start);   
    ofs<<"Elapsed time= " << std::setprecision(6) <<elapsed<< "(s)"<<std::endl;        
    ofs.close();
    return 0;
}

Output:

Elapsed time= 1(s)

any suggestion?

You have to use std::fixed and std::setprecision :

ofs << "Elapsed time= " << std::fixed << std::setprecision(6)
    << elapsed << "(s)"
    << std::endl;

Further difftime() returns a double not a float.

double difftime(time_t time1, time_t time0);

The difftime() function returns the number of seconds elapsed between time time1 and time time0 , represented as a double .

You need to insert std::fixed into the stream if you want 0.000000 , along the lines of:

ofs << "Elapsed time = "
    << std::setprecision(6) << std::fixed << elapsed << " (s)"
    << std::endl;

This gives you:

Elapsed time = 0.000000 (s)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM