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.