Trinity
Trinity

Reputation: 484

How to read a file in c++ without reading every line two times

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;
        }
    }

Upvotes: 1

Views: 94

Answers (1)

kvorobiev
kvorobiev

Reputation: 5070

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;

Upvotes: 4

Related Questions