0

i want to make a code to open .txt file first 10 lines to find a specific file and then if I'm not sure if that's the file which I need it will output a specific number of lines to find a required file. But when I'm typing in the lines number it output whole text file.

#include <iostream>
#include <fstream>
using namespace std;
#define COL_WIDTH 80
int main()
{
    int x;
    int c;
    char filename[FILENAME_MAX];
    char input_line[COL_WIDTH + 1];
    cout << "File name: ";
    cin.getline(filename, FILENAME_MAX);
    ifstream reader(filename);
    if (!reader)
    {
        cout << "Klaida! Failas: " << filename << " file couldn't be opened.";
        cout << endl;
        cin.get();
        return -1;
    }
    while (true)
    {
        for (int i = 1; i <= 10 && !reader.eof(); i++)
        {
            reader.getline(input_line, COL_WIDTH);
            cout << input_line << endl;
        }
        if (reader.eof())
        {
            break;
        }
        cout << "MORE? 'y'" << endl;
        cout << "EXIT 'Q' + ENTER" << endl;
        cin.getline(input_line, COL_WIDTH);
        c = input_line[0];
        if (c == 'y' || c == 'Y') {
            cout << "number of rows: "; cin >> x;

            for (int i = 1; i <= x && !reader.eof(); i++)
            {
                reader.getline(input_line, COL_WIDTH);
                cout << input_line << endl;
            }
        }
        else if (c == 'Q' || c == 'q')
        {
            break;
        }
    }
    return 0;
}
user4581301
  • 29,019
  • 5
  • 26
  • 45
  • 1
    Recommended reading: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). You're doing something slightly different, but the end results will be just as broken and the solution is the same. – user4581301 Dec 15 '19 at 00:59
  • 1
    You need to use only `std::getline` or `>>` to read from `std::cin`, and not a combination of the two, unless you take very, very specific steps to make it work. Your code uses a combination of the two without taking those specific steps. This is in addition to the end-of-file bug that was already mentioned. See the linked answer for more information. – Sam Varshavchik Dec 15 '19 at 01:25

0 Answers0