64,683
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
//格式输出参数
const int COLCOUNT = 3; //列数
const int COLWITDH = 20; //列宽(字符)
const int LINESIZE = COLCOUNT * COLWITDH;
//////////////
// 记录数据在文件中的位置段
/////////////
struct DataReg
{
long begin; //数据在文件的开始位置
long end; //数据在文件中的结束位置
};
//
// 根把 titlName 从源文件中取得数据位置段
//
DataReg getDataReg(ifstream & ifs, string titlName);
//
// 格式化输出指定的数据,并自动排列
// ofstream & ofs : 输出目标文件
// ifstream & ifs : 源数据文件
// DataReg dr : 数据在源数据文件中的位置段
void formatOuput(ofstream & ofs, ifstream & ifs, DataReg dr);
int main (int argc, char * const argv[])
{
ifstream ifsFile("data.txt"); //原数据文件
ofstream ofsFile("format.txt"); //输出数据
ofsFile<<setiosflags(ios_base::left);
ofsFile << setw(COLWITDH)<< " CD" << setw(COLWITDH)<< " DP" << setw(COLWITDH)<< " GO" << endl;
DataReg drCD = getDataReg(ifsFile, "CD"); //定位 CD 数据段
formatOuput(ofsFile, ifsFile, drCD); //读取并输出到第一列
DataReg drDP = getDataReg(ifsFile, "DP"); //DP 数据
formatOuput(ofsFile, ifsFile, drDP); //读取并输出到下一列
DataReg drGO = getDataReg(ifsFile, "Go"); //Go 数据
formatOuput(ofsFile, ifsFile, drGO);
ifsFile.close();
ofsFile.close();
return 0;
}
DataReg getDataReg(ifstream & ifs, string titlName)
{
DataReg dr;
string tmp;
titlName = "TITL " + titlName; //根据源文件数据格式,使用 TITL XXX 来查找。
ifs.seekg(0, ios_base::beg);
while (!ifs.eof())
{
//读取一行,并查找 TITL XXX
getline(ifs, tmp, '\n');
if(tmp.find(titlName, 0) == 0) break;
}
//数据在 TITL XXX 下面第6行,所以这里空跳5行。(有没有跳行函数??)
for (int i=0; i<5; ++i) getline(ifs, tmp, '\n');
dr.begin = ifs.tellg(); //数据段开头
//-----
// 查找数据结尾,(我的测试文件的数据是一行过以空格开分,所以只查找一个 \n )
// (程序中没有用到这个数据,是可有可无的,但为了完整性所以写上)
char ch;
while (ifs.get(ch) && ch!='\n') continue;
dr.end = ifs.tellg();
dr.end--;
return dr;
}
//////////
// 输出
// 采用先输出占位空白字符,再用 seekp 来定位填数据
//////////
void formatOuput(ofstream & ofs, ifstream & ifs, DataReg dr)
{
static long sMaxRow = 0; //记录输出的最大行数
static int sCol=0; //自动分配排列
sCol++;
float data;
ifs.seekg(dr.begin);
ofs.seekp(LINESIZE + sCol * COLWITDH);
long step = LINESIZE - COLWITDH + 1;
long row = 0;
while (ifs >> data)
{
row++;
if (1 == sCol)
{
ofs << setw(LINESIZE) << data << endl;
}
else
{
if (row < sMaxRow)
{
ofs << setw(COLWITDH) << data;
ofs.seekp(step, ios_base::cur);
}
else
{
ofs << setw(COLWITDH) << data << setw((COLCOUNT - sCol) * COLWITDH) << "" << endl << setw((sCol-1) * COLWITDH) << "";
}
}
}
sMaxRow = sMaxRow > row ? sMaxRow : row;
ifs.clear();
}