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.
/* 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>
usingnamespace 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;
}
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
usingnamespace 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;
}