I need help making C++ code. I need help writing a program that asks the user for the name of a text file. The program should display the first 10 lines of the file on the screen. If the file has less than 10 lines, the entire file should be displayed along with a message indicating the entire file has been displayed.

EBK JAVA PROGRAMMING
9th Edition
ISBN:9781337671385
Author:FARRELL
Publisher:FARRELL
Chapter13: File Input And Output
Section: Chapter Questions
Problem 10PE
icon
Related questions
Question

I need help making C++ code. I need help writing a program that asks the user for the name of a text file. The program should display the first 10 lines of the file on the screen. If the file has less than 10 lines, the entire file should be displayed along with a message indicating the entire file has been displayed. 
I have the code but I'm getting build errors. Also can you submit a screen shot of the code running.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//main function of the program
int main()
{
//variable to store file handle and file name
fstream file;
char filename[50];
int line_count = 0;

//Ask user to enter the name of file to read
cout << "Enter the name of the file: " << endl;
cin.getline(filename, 50);

//open a file to perform read operation
file.open(filename, ios::in);
//check if file open is success
if (file.is_open())
{
//variable to read the line
string line;

//read data from file object and put it into string.
while (getline(file, line))
{
//print the line
cout << line << "\n";
line_count += 1;
if (line_count >= 10)
{
break; #break if line count greater than 10
}
}
//close the file .
file.close();

//If the file has less than 10 lines
if (line_count < 10)
{
//print message entire file has been displayed.
cout << "\nEntire file has been displayed" << endl;
}
}
else
{
cout << "\nFile doesn't exist";
}
}

Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 2 steps with 2 images

Blurred answer
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
EBK JAVA PROGRAMMING
EBK JAVA PROGRAMMING
Computer Science
ISBN:
9781337671385
Author:
FARRELL
Publisher:
CENGAGE LEARNING - CONSIGNMENT
C++ for Engineers and Scientists
C++ for Engineers and Scientists
Computer Science
ISBN:
9781133187844
Author:
Bronson, Gary J.
Publisher:
Course Technology Ptr