Displaying the first 10 words from txt file

I need to make a program that can read the first 10 line of words from a txt file.
So far I have this code but still won't read the file properly.
Also, I pause the program since it always kick out before the program fully complete.
please help, thank you in advance.

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
60
61
62
63
64
65
66
67
/* File Head Program
This program will ask user for the name of a file
and will display the first 10 lines of the file on screen
*/

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

int main()
{
	char ch;
	cout << "This program will display the first 10 lines of a program.\n";
	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";

	}

	string line;
	int counter = 0;

	while (getline(file, line))
	{
		++counter;
	}
	file.close();

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

	if (counter < 10)
	{
		cout << "\nThe file has fewer than 10 lines, the entire file will now be displayed below:\n\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 (counter <= 10)
			{
				(getline(file, line));
				cout << line << endl;
				++counter;
			}
	}
	system("pause");
	cout << "This program has paused. Press Enter to continue. \n";
	cin.get(ch);
	cout << "It has paused a second time. Please press Enter again. \n";
	ch = cin.get();
	cout << "It has paused a third time. Please press Enter again. \n";
	cin.get();
	cout << "Thank you!";
	return 0;
	}
Last edited on
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
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int main() {
	cout << "This program will display the first 10 lines of a program.\n";
	cout << "Please enter the name of the file: ";
	string nameFile;
	getline(cin, nameFile);

	ifstream file(nameFile);
	if (!file) {
		cout << "The input file could not be found!\n";
		return 1;
	}

	string line;
	for (int i = 0; i < 10; i++) {
		if (!getline(file, line))
		    break;
		cout << line << endl;
	}

	system("pause");

	return 0;
}

when I run the program and input the file name, do I need to put .txt?
Last edited on
Hello luiz5z,

Either from the keyboard when the file name is entered or by the program if that is part of the file name.

Andy
Topic archived. No new replies allowed.