(2)读入一个C++程序,使程序中的所有左花括号“{”和右花括号“}”都单独占一行,新程序保存到另一个.cpp文件中,并在屏幕上显示处理过的程序,显示时加上行号。
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
char ch1='\0',ch2,out[256];
int i=0;
ifstream infile("source.cpp",ios::in);
//测试是否成功打开,打开失败时(如要读的数据文件不存在)退出
ofstream outfile("out.cpp",ios::out);
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
if(!outfile)
{
cerr<<"open error!"<<endl;
exit(1);
}
while(!infile.eof())
{
infile.get(ch2);
if((ch2=='{'||ch2=='}')&&(ch1!='\n'))
outfile<<'\n';
else if((ch1=='{'||ch1=='}')&&(ch2!='\n'))
outfile<<'\n';
outfile<<ch2;
ch1=ch2;
}
infile.close(); //读入完毕要关闭文件
outfile.close();
ifstream view("out.cpp",ios::in);
if(!view)
{
cerr<<"open error!"<<endl;
exit(1);
}
while(!view.eof())
{
view.getline(out,255,'\n');
cout<<out<<endl;
}
return 0;
}
图片:
心得:
ORZ。。。忘记getline的终止符是不会输出的了,果然还是应该在做项目之前再看看视频,都忘了