C Program That Numbers the Lines of a Text File

II Create a listing of a file in which each line is numbered, and each
// page has a heading showing the file name and the page number.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
const int LINES_PER_PAGE = 50;
void headerf ofstream&, const string&, int );
int main()
{
string line; // one line from input file
string inName, outName; // names of input and output files
int lineNum = 1 ; // listing line number
int pageNum = 1 ; // listing page number
cout « "Create listing of which file? ";
cin » inName;
cout « "Put listing in which file? ";
cin » outName;
ifstream in( inName.c_str(), ios::in );
ofstream out( outName.c_str(), ios::out );
header( out, inName, pageNum++ );
getline( in, line );
while (!in.fail()) {
out « setw( 4 ) « lineNum « " " « line « endl;
if (lineNum % LINES_PER_PAGE == 0) {
out « 'f' ;
header( out, inName, pageNum++ );
}
++lineNum;
getline( in, line );
}
cout « "Listing of " « inName « " on " « outName « " complete."
« endl;
out.close( ) ;
return 0;
// Output a page header consisting of file name (underlined) and
// page number.
//
void header( ofstream& out, const strings name, int page )
{
int nameLen;
int width;
nameLen = name.length() ;
width = 70 - nameLen;
out « name « ' r ' ;
for (int i = 0; i < nameLen; ++i)
out « '_' ;
out « setw( width ) « "Page " « page « endl « endl;
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.