I am working on this program, but it seems it is not working...it makes sense for me so I do not know what I am doing wrong, I will appreciate some help figuring out what is wrong and how to fix it.
The program has to ask the user for a file name and display the first 10 lines then if there are less than 10 lines it should display the entire file with a message indicating that the entire file has been displayed.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
//Variables
ifstream file;
string fileName;
string line;
int counter = 0;
//1. Ask user for the name of a text file
cout << "Please enter the name of the text file you want to open: " << endl;
while (true)
{
getline(cin, fileName);
file.open(fileName.c_str());
//Check if file open was successful
if (!file)
{
cout << "Error: cannot open the file " << fileName << endl;
exit(1);
}
}
//2. Display the first 10 lines
while (getline(file, line))
{
counter++;
if (counter > 1 && counter < 10)
{
cout << line << endl;
cout << "The file has less than 10 lines." << endl;
cout << "The entire file has been displayed!" << endl;
}
elseif (counter > 1 && counter > 10)
{
cout << line << endl;
}
else
{
break;
}
}
//3. CONDITION: if the file has fewer than 10 lines the entire file
//should be displayed along with a message indicating the entire file
//has been displayed.
system("pause");
return 0;
}
//1. Ask user for the name of a text file
cout << "Please enter the name of the text file you want to open: " << endl;
getline(cin, fileName);
file.open(fileName.c_str());
//Check if file open was successful
if (!file)
{
cout << "Error: cannot open the file " << fileName << endl;
exit(1);
}
int main()
{
//Variables
ifstream file;
string fileName;
string line;
int counter = 0;
//1. Ask user for the name of a text file
cout << "Please enter the name of the text file you want to open: " << endl;
getline(cin, fileName);
file.open(fileName.c_str());
//2. Display the first 10 lines
while (getline(file, line))
{
counter++;
//Check if file open was successful
if (!file)
{
cout << "Error: cannot open the file " << fileName << endl;
exit(1);
}
elseif (counter > 1 && counter < 10)
{
cout << line << endl;
cout << "The file has less than 10 lines." << endl;
cout << "The entire file has been displayed!" << endl;
}
elseif (counter > 1 && counter > 10)
{
cout << line << endl;
}
else
{
break;
}
}
//3. CONDITION: if the file has fewer than 10 lines the entire file
//should be displayed along with a message indicating the entire file
//has been dipalyed.
system("pause");
return 0;
}