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++ - 保存和加载函数指针到文件

c++ - 声明 constexpr 函数或方法

C++ ofstream删除和清理

c++ - 我可以使用在类构造函数中初始化的ofstream类型的成员变量吗?

c++ - 无法访问私有(private) std::fstream 成员?

c++ - 与复合物体的圆碰撞

c++ - 可组合的 monadic lambda/std::function with std::optional

c++ - std::vector 的容量如何自动增长?费率是多少?

c++ - 使用 ofstream 保存文本文件的困难

c++ - C#相当于C++中的ifstream/ofstream