1

I'm trying to write a C++ code that reads the file with x-y data (example file shown below)

1.0,10.0
2.0,10.0
3.0,20.0
4.0,20.0
5.0,10.0
6.0,10.0

Since these are experimental data I made a struct which makes it easier to read, when I put all the data into an array. I successfully open the file. However, when I created a loop that was going to put the data into an array I am stuck with an infinite loop. How could I fix this? Also, is there a way to dynamically assign the size of an array (maybe vector) that would automatically change it size according to the file length?

My code is as follows:

#include <iostream>
#include <fstream>
#include <istream>

struct point{
    float x, y;
};


int main(void)
{
    std::string input_fn = ("testdata.txt");
    std::string output_fn = ("output.txt"); 

    std::ifstream input_data;  
    input_data.open(input_fn.c_str());                              //opening an input file
    while(input_data.fail()){                                       //checking if file exists
        input_data.close();
        std::cout << "Incorrect filename, try again\n";
        std::cin >> input_fn;
        input_data.open(input_fn.c_str()); 
    }

    //float x[2000];
    //float y[2000];
    point pttable[2000];

    int i = 1;
    input_data.clear();                                             // clear stream flags and error state
    input_data.seekg(0, std::ios::beg);
    while (!input_data.eof()){                                      //this is the faulty infinite loop                          
    input_data >> pttable[1].x >> pttable[1].y;
    std::cout<<i;
    i++;
    }
    delete &i;

    input_data.close();

return 0;
}
Yess
  • 21
  • 2
  • [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) `delete &i;`? – KamilCuk Nov 15 '19 at 09:44

1 Answers1

1

It could be possible that read operation failed in that case it will set the failbit and not necessarily the eof bit. So it advisable to loop until the read fails. There are multiple posts on StackOverflow expalining when to use EOF.

Hope these references will help.

Differences between eof and fail

How does ifstream's eof() work?

Replace your faulty while loop with:

while(true)
{
    if(!(input_data >> pttable[1].x >> pttable[1].y))
        break;

    std::cout<<i;
    i++;
}
abhilb
  • 5,069
  • 2
  • 14
  • 24
  • Thank you, additionally, when I replaced comma with a tab as a separator in the input file, the code finally worked! – Yess Nov 15 '19 at 10:25