I used eof() and good() function but there is no change in the output.
They're both wrong, so I'm not surprised. The problem is that both eof() and good() will only switch state after you've tried to read from the file and that attempt fails. So you need some way to check the state after reading but before processing what was read, otherwise you'll accidentally process the previously read item again.
Convention is this:
while (infile2 >> n)
cout << '\n' << n;
The extraction operator will return a reference to the stream object, which when used in boolean context will give you the current state. Alternatively you can still use the eof() or good() option, but a conditional inside the loop is needed:
while (infile2.good()) {
if (!infile2.good())
continue;
cout << '\n' << n;
}
That's redundant, verbose, and logically confusing, so I don't recommend it.
deceptikon
Challenge Accepted
3,452 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 57
but the second method is not working it is printing the last entered number infinitely..
My bad, I forgot to include the actual input request:
while (infile2.good()) {
infile2 >> n;
if (!infile2.good())
continue;
cout << '\n' << n;
}
deceptikon
Challenge Accepted
3,452 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 57
Question Answered as of 6 Months Ago by
deceptikon Thanks again, it works........
Please don't use that longer loop for anything but your own instruction. The conventional method is strongly recommended.
I think In if statement we are checking the next position is good or not?
No, we're checking if the previous input request tried to read of the end of the stream or encountered an error.
deceptikon
Challenge Accepted
3,452 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 57