0

I'm getting wrong output using fstream.

I create a text file with 3 words in it. When I run the program from a text file I got the last word in the output twice (The word Apple I got twice in the output). I don't know why.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string fruit;
    int point = 0;

    ifstream infile;
    infile.open("darbas.txt");

    while(!infile.eof()){
        infile >> fruit;
        cout << fruit << endl;
        point++;
    }

    cout << "The number of fruit: " << point <<  endl;
    infile.close();

    return 0;
}

I expect the output to be

Banana, Orange, Apple, The number of fruit: 3

Actual output:

Banana, Orange, Apple, Apple, The number of fruit: 4

Oliort
  • 1,360
  • 11
  • 27
hey man
  • 1
  • 1
  • 3
    Yay finally it's an exact dupe! – Lightness Races in Orbit Jul 31 '19 at 11:48
  • Now I tried to put infile >> fruit in !infile.eof() place, but the output was still wrong. It was Orange, Barana, The number of fruit: 2. Why It's still wrong. – hey man Jul 31 '19 at 12:25
  • Because you did not fully read the page I linked you to. You probably have two `infile >> fruit` now so you're discarding every other input. (Though it's not possible for Orange to be first, and now it's spelt "Barana"? Pay attention to details to avoid confusing the issue.) – Lightness Races in Orbit Jul 31 '19 at 12:30
  • Yes It's really true. I missed It somehow. Thank you, but how could I change It. – hey man Jul 31 '19 at 12:34
  • So you recognise the error but can't see how to fix it? I'll let you think for a while about how to do that, and about what each line of code in your program does. – Lightness Races in Orbit Jul 31 '19 at 12:35
  • If you don't mind me asking, what made you think `while(!infile.eof()){` was correct? We see this error over and over again, but why beginners make this mistake isn't usually clear. – john Jul 31 '19 at 12:45
  • I did It. Thanks that you let me to think about It. – hey man Jul 31 '19 at 12:55
  • @john I wached video on youtube and that man's code was good with !infile.eof(). Can you say me where !infile.eof() is usefull? – hey man Jul 31 '19 at 12:58
  • That man didn't know what he was talking about. The only time that `eof` is useful is when you know that a read has failed and you want to find out why it has failed. `eof` does not tell you if you are currently positioned at the end of file. So it's something you would use **after** you tried to read something, to tell you how that read went, not something you would use **before** you read, to tell you how the next read might go. – john Jul 31 '19 at 13:56
  • @John Thanks for your help. – hey man Jul 31 '19 at 14:12

0 Answers0