/*
打开指定的一个文本文件,在每一个行前加行号。
*/
#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<iomanip> //cout<<setw() 输出格式控制
using namespace std;
int main(){
/*(1)打开输入文件*/
ifstream infile;
infile.open("abc.txt");//outfile.open("abc.txt",ios::in); //默认方式
if(infile.fail()){
cout<<"输入文件abc.txt打开失败!\n";
exit(1);
}
/*(2)打开输出文件*/
ofstream outfile;
outfile.open("abc_back.txt",ios::out);
if(outfile.fail()){
cout<<"输出文件abc_back.txt打开失败!\n";
exit(1);
}
/*(3)复制行,并在行头添加行号*/
int num_line=1; //行号计数器
char buffer[256]; //行拷贝缓冲区
//cout<<"sizeof(buffer)="<<sizeof(buffer)<<endl;
while(!infile.eof()){
/*(3.1)读取1行*/
if (!infile.getline(buffer, sizeof(buffer))){
//cout<<"已经到达文件结尾,文件读取失败,退出循环!";
break;
}
/*(3.2)写出构造的新行*/
//**************************************
while(infile.getline(buffer,256))
{
//in.get();
cout << num_line++ << ":" ;
cout << buffer <<endl;
}
//======================================
}
/*(4)文件关闭*/
infile.close();
outfile.close();
cout<<"操作成功,程序结束!\n";
}
首先要在该cpp文件所在目录文件建一个abc,然后编译运行后会出现一个abc_back的txt文件。再将所需分行内容输入abc.txt中,编译运行后abc_back即为分行后的txt文件。细节不懂可留言提问。