File Head Program Write a program that asks the user for the name of a file. The program should display the first 10 lines of the file on the screen (the “head” of the file). If the file has fewer than 10 lines, the entire file should be displayed, with a message indicating the entire file has been displayed.
Need help and guidance in code, it doesn't display on the content of the file.
int main() {
fstream file;
int max = 0;
string str;
file.open("name.txt", ios::in);
if(file.fail()) {
cout << "file is not open" << endl;
}
while(getline(file, str)) {
max++;
}
cout << "number of line are " << max << endl;
while(getline(file, str)) {
cout << str << endl;
if(max >= 10) {
break;
}
}
file.close();
}
look at lines 11 and 16
for the loop in line 11 to end, the reading operation must fail, so I don't understand how you expect it to work later at line 16
alright, its mean, line 11 makes program to come at the end of the file ??
after the in line 16 it will get nothing ?
can you guide me what to do here ?
i just sollved it with
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
I found the second link to be the most help.
First you missed the include files at the top of your program. It is best to include the whole program so people do not have to guess at what you did.
As ne555 has pointed out the first while loop reads you file until the "eof" bit is set on the stream. When you reach the second while loop the stream is in a failed state and the second while loop does not work.
before the second while loop you need to reset the state bits on the stream and reposition the file back to the top before you can read it again.
For the if statement if(max >= 10). Really. Unless it is a short file "max" is always going to be "> 10". When I first ran the program it printed one line and left the while loop.
In the instructions I see that you have to prompt the user to enter a file name, which you have not done. And if less than ten lines are in the file that you should print a message that the entire file has printed, which you have not done. No where did I see where you have to count the maximum number of lines in the file.
Your program could be done with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
if (!inFile)
{
std::cout << "\n file \"" <<inFileName<<"\" did not open." << std::endl;
return 1;
}
for (size_t lc = 0; std::getline(inFile, str) && lc < MAXLINES; lc++)
{
std::cout << str << std::endl;
count++;
}
if (count < MAXLINES)
std::cout << "\n Entire file has printed.\n" << std::endl;