Write a program that displays the first ten lines of a file

Write a program that asks the user for the name of a file. The program should display the first ten lines of the file on the screen. If the file has fewer than 10 lines, the entire file should be displayed with a message indicationg the entire file has been displayed. This is what I have. I put an example txt file where the cpp file is stored. I input the the file name but it always returns....cant find this file. Any suggestions?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 #include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int main() {
cout << "Please enter the name of the file: ";
string nameFile;
getline(cin, nameFile);

fstream file(nameFile, ios::in);

if(file.fail())
{
cout<<"The input file could not be found!\n";
exit(1);
}

string line;
int counter=0;
while(getline(file, line))
{
++counter;
}

cout<<endl<<counter<<endl;
file.close();

file.open(nameFile, ios::in);

if(counter<10)
{
cout<<"\nThe file has fewer than 10 lines, the entire file will be displayed\n";
while(getline(file, line))
{
cout<<line<<endl;
}
}
else
{
counter=1;
cout<<"\nThe file has more than 10 lines. Here are the first 10 lines\n";

while(getline(file, line))
{
if(counter<=10)
{
cout<<line<<endl;
}
else if(counter > 10)
{
break;
}
++counter;C:\Users\User\Desktop\programming110\test\main.cpp
}
}
}
fstream class takes a c string as a parameter

change line 12 to :
fstream file(nameFile.c_str(), ios::in);
Last edited on
thank you.
\
Topic archived. No new replies allowed.