第十四周项目4 - 处理C++源代码的程序(m后n行加注释)

(3)读入一个C++程序,输入m、n两个数字,从第m行起的n行代码将作为注释使用(即在这些行前面加上”//”),新程序保存到另一个.cpp文件中,并在屏幕上显示处理过的程序,显示时加上行号。

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
    char ch1='\0',ch2,out[256],line[256];
    int i=0,m,n;
    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);
    }
    cout<<"输入两个数m,n,从第m行起的n行代码将作为注释使用:";
    cin>>m>>n;
    cout<<endl;
    int j=1;
    while(!infile.eof())
    {
        infile.getline(line,255,'\n');
        if(j>=m&&j<m+n)
        {
            outfile<<'/'<<'/';
        }
        outfile.write(line,strlen(line));
        outfile<<endl;
        ++j;
    }
    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<<++i<<'\t'<<out<<endl;
    }
    view.close();
    return 0;
}
图片:


心得:

由上个程序更改而来。。。感觉终于顺手一回

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值