c++ - std::ofstream 设置浮点格式的精度

标签 c++ ofstream

我需要将 6 位精度的浮点类型写入文件。 这段代码没有像我预期的那样正常工作:

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;
}

输出:

Elapsed time= 1(s)

有什么建议吗?

最佳答案

你必须使用 std::fixedstd::setprecision :

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

进一步difftime()返回 double 而不是 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.

关于c++ - std::ofstream 设置浮点格式的精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45609911/

相关文章:

c++ - ofstream variable.open 是否支持预先确定的字符串变量?

c++ - C++上INT16的二进制写法

C++模板混淆

c++ - 如何为流式自写类编写用户定义的操纵器

c++ - vector 中的C++ push_back

c++ - i686-elf-gcc CreateProcess 错误(没有那个文件或目录)

c++标准库列表用法?

c++ - ofstream 创建一个文件但不能写入它

c++ - 在线程中写入文件,C++

c++ - ofstream 变量不能出现在 OpenMP firstprivate 中?