1

I have a problem reading file by using c++.The file which contains a float number at every line as following

1.33
5.45
6.21
2.48
3.84
7.96
8.14
4.36
2.24
9.45

My code is reading and printing everyline and printing it two times.How can i fix it?

    string line;
    fstream inputNumbersFile("input.txt");

    if (inputNumbersFile.is_open())
    {   
        while (!inputNumbersFile.eof())
        {
            getline(inputNumbersFile, line);
            cout << line << endl;
        }
    }
tivn
  • 1,785
  • 10
  • 13
Trinity
  • 436
  • 5
  • 21
  • 2
    Aside: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – πάντα ῥεῖ Apr 18 '15 at 15:40
  • Have you stepped through your code with a debugger to see what it's doing? This is what you should start with in a problem like this. It'll probably shed some light on your issue. – Steve Apr 18 '15 at 15:43
  • I just built this with GCC 4.6.3 on Linux, using your input data, and it works fine for me. – Steve Apr 18 '15 at 15:45
  • Yes, i have stepped through my code with debugger.And it executes geline statement two times in while loop. – Trinity Apr 18 '15 at 15:46
  • Do you mean the last line empty line is printed? It works for me, especially with the fix in the answers. – csl Apr 18 '15 at 15:48
  • I suspect you've described the output wrongly: you should just post the output rather than trying to describe it. (and also, for your input file, say whether the last line has a newline at the end or not, assuming you know how to find out) –  Apr 18 '15 at 15:49
  • The following code worked. I couldn't understand what's wrong! Thanks guys! – Trinity Apr 18 '15 at 15:52

1 Answers1

4

Using of inputNumbersFile.eof() in loop condition is a bad idea. Just replace this loop with something like

while (getline(inputNumbersFile, line))
    cout << line << endl;
kvorobiev
  • 4,801
  • 4
  • 27
  • 33