【C++】 ofstream列对齐和设置小数点精度

https://blog.csdn.net/ahhsqmyzwby/article/details/51570234

最近工程项目中,需要对输出的文件的格式作要求。因为每一行有很多列,每一列空格隔开,代表一个column,存放数字。

查找了一些资料得到如下:

1、需要使得每一列右对齐。

注意头文件

#include<iomanip>

ofstream ostrm;
    ostrm.open("test2.txt");
    for(i=0;i<10;i++)
    {
        ostrm<<setiosflags(iOS::left)<<setw(10)<<setfill('*')<<i<<endl;
    }

就可以生成如下效果,这里是left,改成right即可,10和*的含义也是一看就懂。

0*********
1*********
2*********
3*********
4*********
5*********
6*********
7*********
8*********
9*********


2、需要设置显示的精度,也就是将小数点后面的0补齐,这里也是和cout的流输出类似。

 ofstream fout("out.txt");
    fout.setf(ios::fixed, ios::floatfield);  // 设定为 fixed 模式,以小数点表示浮点数
    fout.precision(2);  // 设置精度 2

猜你喜欢

转载自blog.csdn.net/chengde6896383/article/details/83790380