This program is supposed to take a file name entered by the user, open it, and display the first 25 lines. When I run the program it displays all the lines in the file (it has 30 lines). I have tried changing the number of lines it displays (line 34) and I get strange results. If I change it to 2 then the program will display 4 at first, then 2 every time I push a key after that. What am I missing? This seems like it should be simple but I'm not seeing it. Any ideas?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
usingnamespace std;
int main()
{
string line;
fstream nameFile;
string filePath;
cout<< "Please enter the file path you wish to open."<<endl;
cout<< "File path: ";cin>>filePath;
nameFile.open(filePath, ios::in);
if(nameFile)
{
int counter = 0;
//the loop below is supposed to display
//the first 25 lines then pause for the
//user to enter a character to display the
//next 25 lines
while(!nameFile.eof())
{
if (counter >= 25)
{
getchar();
counter = 0;
}//end if
getline(nameFile, line, '\n');
cout<<line<<endl;
counter++;
}//end while
nameFile.close();
}//end if
else
{
cout<<"ERROR: Cannot open file.\n";
}//end else
return 0;
}//end main
I forgot to say that the program is supposed to pause after the 25th line and wait for the user to push a button on the keyboard to see the next 25 lines. I displayed the variable counter and noticed that after 25 lines, it reset to 0 like it is supposed to but the program didn't pause. Why not? I thought that the getchar() function was supposed to pause the program till a key was pushed. Am I not understanding this correctly?
Also, don't loop on `eof', loop on the reading operation. while( getline(nameFile, line, '\n') )
> If I change it to 2 then the program will display 4 at first, then 2 every time I push a key after that http://www.cplusplus.com/forum/beginner/114875/#msg627086
`getchar()' is taking that carriage return of when you wrote the file name
Unfortunately it looks like I was writing my last post while you were working to find an answer for me. That worked and I do appreciate the help! However I need the program to pause after the first 25 lines, then display the next 25 after the user has pushed a button on the keyboard. I think my problem lies somewhere in the getchar() call , but I'm not sure. What do you think?
Thanks all! ne555 your link was very helpful. I just needed to insert the cin.ignore() on line 29 to get the program to "clear the buffer" so that the getchar() would work. Thanks!!