下例中make_neat函数有两个流参数:一个是ifstream类型,连接到一个输入文件rawdata.txt的流。另外一个是ofstream类型的流,连接到一个输出文件neat.txt的流。
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<iomanip>
using namespace std;
void make_neat(ifstream& messy_file, ofstream& neat_file, int number_after_decimalpoint, int field_width);
//前条件:messy_file和neat_file这两个流已经用open函数连接到文件。
//后条件:将与messy_file流连接的那个文件中的内容写到屏幕上。
//同时也写到与neat_file流连接的文件中。
//每个数字单独占一行,并采用定点计数法,不采用e计数法。
//在小数点后保留number_after_decimalpoint位小数。
//在每个数字之前要么加一个正号,要么加一个负号。
//每个数字都要占用fild_width的一个域宽。(该函数不关闭文件)
int main()
{
ifstream fin;
ofstream fout;
fin.open("rawdata.txt");
if(fin.fail())
{
cout << "input file opening filed.\n";
exit(1);
}
fout.open("neat.txt");
if(fout.fail())
{
cout << "output file opening filed.\n";
exit(1);
}
make_neat(fin, fout, 5, 12);
fin.close();
fout.close();
cout << "end of program.\n";
return 0;
}
//使用iostream,fstream,iomanip:
void make_neat(ifstream& messy_file, ofstream& neat_file, int number_after_decimalpoint, int field_width)
{
neat_file.setf(ios::fixed);
neat_file.setf(ios::showpoint);
neat_file.setf(ios::showpos);
neat_file.precision(number_after_decimalpoint);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout.precision(number_after_decimalpoint);
double next;
while (messy_file >> next)
{
cout << setw(field_width) << next << endl;
neat_file << setw(field_width) << next << endl;
}
}