61.5k views
2 votes
In C++ :

Write a program that asks the user for the name of a file. The program should display the contents of the file on the screen. Each line of screen output should be preceded with a line number, followed by a colon. The line numbering should start at 1. Here is an example:
1:George Rolland
2:127 Academy Street
3:Brasstown, NC 28706
If the file’s contents won’t fit on a single screen, the program should display 24 lines of output at a time, and then pause. Each time the program pauses, it should wait for the user to strike a key before the next 24 lines are displayed.

1 Answer

2 votes

Answer::

//Program is written in C++ Programming Language

// Comments are used for explanatory purpose

#include

#include

#include

#include

using namespace std;

int main(){

ifstream file; // File stream object

string name; // To hold the file name

string inputLine; // To hold a line of input

int lines = 0; // Line counter

int lineNum = 1; // Line number to display

// Get the file name.

cout << "Enter the file name: ";

getline(cin, name);// Open the file.

file.open(name.c_str());// Test for errors.

if (!file){

// There was an error so display an error

// message and end the PROGRAM.

cout << "Error opening " << name << endl;

exit(EXIT_FAILURE);

}

// Read the contents of the file and display

// each line with a line number.

// Get a line from the file.

getline(file, inputLine, '\\');

while (!file.fail()){

// Display the line.

cout << setw(3) << right << lineNum<< ":" << inputLine << endl;

// Update the line DISPLAY COUNTER for the next line.

lineNum++;// Update the total line counter.

lines++;// If we've displayed the 24th line, pause the screen.

if (lines == 24){

cout << "Press ENTER to CONTINUE...";

cin.get();

lines = 0;

}

// Get a line from the file.

getline(file, inputLine, '\\');}

//Close the file.

file.close();

return 0;}

User Smokefoot
by
3.6k points