0

for example, there are 100 lines from the file, and I only want to show 20 lines and ask the user to press enter and then another 20 line display and so on to the end of the file.

here is my code

    int main()
    {
     ifstream infile;
      string filename;
      string line;
      int lineCount = 0;

      cout << "Enter file name: \n";
      cin >> filename;

      system("cls");

      infile.open(filename);


      if (!infile) 
      {
       cout << "\nErrors\nNo file exist.\n";
        exit(1);
      }
      else 
      {

       while (infile.good())
       {
        lineCount++;

         getline(infile, line);

         cout << lineCount << ":\t" << line << endl;
       } 
      }
      return 0; 
      }
Luna Thao
  • 3
  • 1

1 Answers1

2

You just have to count the lines. Example:

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

int main()
{
    ifstream infile;
    string filename;
    string line;
    int lineCount = 0;

    cout << "Enter file name: \n";
    cin >> filename;

    system("cls");

    infile.open(filename);


    if (!infile)
    {
        cout << "\nErrors\nNo file exist.\n";
        exit(1);
    }
    else
    {

        while (getline(infile, line))
        {


            cout << lineCount << ":\t" << line << endl;

            if (lineCount % 20 == 0) {
                cout << "Press Enter To Read 20 More Lines, Or Type Quit to Exit";
                string response;
                getline(cin, response);
                if (response == "Quit") return 0;

            }
            lineCount++;
        }
    }
    return 0;
}
  • `while (infile.good())` checks to see if the stream is good before reading the stream and finding it isn't. The count may be off by one as a result. Variant of [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125). You need to read, test, and then increment. – user4581301 Apr 29 '21 at 23:38
  • Same problem. You want something more like `while (getline(infile, line))` This will try to read. If it succeeds, the loop enters the body where it processes the line and increments. If not, the loop doesn't enter the body. – user4581301 Apr 30 '21 at 00:04