C++—— 用流函数格式化输出

基本语法

设置一个标志(flag)

cout.setf(ios::fixed);
cout.setf(ios::showpoint);//显示小数点
cout.setf(ios::showpos);//正数显示+

取消一个标志

cout.unsetf(ios::showpos);

操纵元(manipulator)

setprecision

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.setprecision(2);//保留两位小数点
cout << 2 << endl;
  • setprecision用于控制小数位数.

setw

cout << "start" << setw(4) << 10 <<
     << setw(6) << 20;
  • 此处setw 是一个操纵元,endl和它一样,也是一个操纵元。
  • setw即为set width,通过width成员函数可以达到同样的效果,代码如下:
cout << "start now";
cout.width(4);
cout << 7 << endl;
  • 但无论用什么方法,参数的意义是总长度,也就是包含原数据的长度。
  • 在使用setw或者setprecision操纵元时,必须有以下代码:
#include 
using namespace std;

setw和setprecision的作用效果和标志一样,除非在之后重新使用其他的参数,否则其效果将一直延续下去。

完整代码

#include "iostream"
#include "fstream"
#include "cstdlib"
#include "iomanip"

using namespace std;

void Make_Neat(ifstream& Messy_File,ofstream& Neat_File,int Num_after_Decimalpoint,int Field_Width);

int main(int argc, char const *argv[])
{
    ifstream fin;
    ofstream fout;

    fin.open("rawdata.dat");
    if(fin.fail())
    {
        cout << "Input file opening error!" << endl;
        exit(1);
    }
    fout.open("neat.dat");
    if(fout.fail())
    {
        cout << "Output file opening error!" << endl;
        exit(1);
    }

    Make_Neat(fin,fout,5,12);

    fin.close();
    fout.close();

    cout << "end of program.\n";
    return 0;
}

void Make_Neat(ifstream& Messy_File,ofstream Neat_File,int Num_after_Decimalpoint,int Field_Width)
{
    Neat_File.setf(ios::fixed);
    Neat_File.setf(ios::showpoint);
    Neat_File.setf(ios::showpos);
    Neat_File.precision(Num_after_Decimalpoint);
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.setf(ios::showpoint);
    cout.precision(Num_after_Decimalpoint);

    double next;
    while(Messy_File >> next)
    {
        cout << setw(Field_Width) << next << endl;
        Neat_File << setw(Field_Width) << next << endl;
    }
}

你可能感兴趣的:(C++)