Help understanding line in code

So my teacher helped out a bit with this program and I understand it all except for this one line. Can someone explain o me what is happening in the 22 line in the whie loop? Any help is appreciated.

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
  #include <iostream>
#include<string> 

#include<fstream> 

using namespace std; 

int main() 

{string fileName; 
string line; 
cout<<"Enter a file to read"<<endl; 
cin>>fileName; 

fstream inFile;

inFile.open(fileName, ios::in);
int count = 0; 

while (!inFile.eof()){ 

while(getline(inFile,line)&&count<2) 

{ 
cout<<line<<endl; 

count++; 

} 

system("PAUSE");
return 0;

} 

} 
Last edited on
getline returns a reference to inFile. When used in a context where a bool is expected, operator bool is invoked on the stream.

http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool

So, in English, line 22 might look like:

"While we successfully extract a line from the input stream and count is less than 2"
It's very hard to read this code, since there is a lack of indentation.
It turns out that it has nested loops, like this:
1
2
3
4
5
6
7
8
9
10
11
    while (!inFile.eof())
    { 
        while(getline(inFile,line)&&count<2) 
        { 
            cout<<line<<endl; 
            count++; 
        } 

        system("PAUSE");
        return 0;
    } 

The outer loop is pretty much useless, partly because checking for eof() is unnecessary, but mainly because the return 0; will ensure it can never execute more than once.

If we were to write the loop like this:
1
2
3
4
    while (getline(inFile,line) ) 
    { 
        cout << line << endl; 
    } 

then we have a pretty standard way of reading each line from the file and then displaying that line in the output.

When getline() (or most other operations on a stream) are tested as part of a while condition, it evaluates to give a boolean true or false result. If the input operation was successful, (that is a line was read from the file), the result is true, and the body of the loop is executed. If the input fails (whether due to end of file or some other reason), then the result is false and the loop terminates.

In the example code we have this:
1
2
3
4
5
6
7
8
    int count = 0; 
    string line; 

    while (getline(inFile,line) && count<2) 
    { 
        cout << line << endl; 
        count++; 
    } 

Here, the body of the loop is executed only if both conditions are true, that is the getline was successful and the value of count is less than 2. Since the initial value of count is zero, after reading and outputting the first two lines from the file, count will have a value of 2. Thus count<2 will be false and the loop terminates.

The result will be, a maximum of two lines will be read and displayed.
Topic archived. No new replies allowed.