Opening a file, reading lines - NOT working

Attempting an exercise in a textbook: it asks to open a file, ask the user how many lines to display, and to give the option to keep going or quit viewing by means of a letter or converting a number input as char into int through atoi.

My code compiles but doesn't give the correct results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;

int main()
{
    int lines, exitCheck;
    char pathfile[500], inputFile[500], c, check[2];

    cout << "Enter path and filename to open: ";
    cin.getline(pathfile, 500);

    ifstream thefile(pathfile);

    while(true)
    {
        cout << "\nEnter number of lines to read: ";
        cin >> lines;

        for(int i = 1; i <= lines && ( ! thefile.eof() ); i++)
        {
            thefile.getline(inputFile, 500);
            cout << inputFile;
        }

        if( thefile.eof() )
        {
            break;
        }

        cout << "\nMore? (0 or Q to exit): ";
        cin >> check;

        c = check[0];
        exitCheck = atoi(check);

        if(c == 'Q' || c == 'q' || exitCheck == 0)
        {
            break;
        }
    }
    return 0;
}


Problems:
-# of displayed lines != input number, both through iteration 1 and 2 (different # of lines displayed each iteration with same input #).

-after iteration 1 and 2, it just bounces back and forth betw "enter # of lines" and exit prompt w/o displaying anything but those prompts.

-exit prompt works with the accepted values, but only stays within loop using #s

-using ( ! xxxx.eof() ) seems buggy, I've had to put a space betw the "!" and xxxx.eof() or reverted to no space after changing around variables so it would compile [I'm using code::blocks in case that has anything to do w/it].

Those were the visible problems =p.

Your advice and help are greatly appreciated, thanks!
Change the array to a std::string/ try the following out:

1
2
3
4
5
std::string current_line;
while(lines-- || getline(thefile,current_line))
{
    cout<<current_line<<endl;
}

Note that I did not compile it to verify, but it should work.
Last edited on
Topic archived. No new replies allowed.