Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Here is the assignment: Write a program that asks the user for the name of a fil

ID: 3566330 • Letter: H

Question

Here is the assignment:

Write a program that asks the user for the name of a file. The program should display the contents of the file with each line preceded with a line number followed by a colon. The line numbering should start at 1. Additionally, screen output must be written to a file. I have everything working, except I am stuck on the "each line preceded with a line number followed by a colon" part.

Any help would be appreciated. Thanks in advance!

My code is below:

fname = input("Enter complete name of file to be read: ")


#open fname
infile = open(fname, 'r')

#read the file's contents

file_contents = infile.read()

#close the file
infile.close()

print(file_contents)
   
#open a file named write.txt
outfile = open('write.txt', 'w')

#write the names to the file.
outfile.write(file_contents)

#close the file.
outfile.close()

Explanation / Answer

// Get a line from the file.
getline(infile, inputLine, ' ');
while (!infile.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++;
}

// Close the file.
infile.close();
return 0;
}