(2)读入一个C++程序,使程序中的所有左花括号“{”和右花括号“}”都单独占一行,新程序保存到另一个.cpp文件中,并在屏幕上显示处理过的程序,显示时加上行号。
#include <fstream>
#include<iostream>
//#include<string>
#include<cstdlib>
using namespace std;
void outprogram(char *filename);
int main( )
{
char ch1,ch2;
ifstream sourceFile("source.cpp",ios::in);
if(!sourceFile)
{
cerr<<"source code read error!"<<endl;
exit(1);
}
ofstream outFile("newsource.cpp",ios::out);
if(!outFile)
{
cerr<<"new source code write error!"<<endl;
exit(1);
}
ch1='\0';
while(!sourceFile.eof())
{
sourceFile.get(ch2);
if((ch2=='{'||ch2=='}')&&(ch1!='\n'))
outFile.put('\n');
else
if((ch1=='{'||ch1=='}')&&(ch2!='\n'))
outFile.put('\n');
outFile.put(ch2);
ch1=ch2;
}
outFile.close();
sourceFile.close();
cout<<"经过处理后的源程序是:"<<endl;
outprogram("newsource.cpp");
return 0;
}
void outprogram(char *filename)
{
char line[256];
int n = 1;
ifstream inFile(filename, ios::in);
if(!inFile)
{
cerr<<"file open error!"<<endl;
exit(1);
}
while (!inFile.eof())
{
inFile.getline(line,255,'\n');
cout<<n<<'\t'<<line<<endl;
n++;
}
inFile.close();
return;