0

I wrote a parser to calculate a distance matrix out of a coordinate file (number, x, y).

The file looks like this:

1 41 49

2 35 17

3 55 45

4 55 20

Each line represents a city, with its coordinates (x,y) following.

This is the parser. The countLines() function just takes a file and returns the number of lines.

void parseCoords(string file){

ifstream tspCoordFile;
ifstream tspCoordFile2;
tspCoordFile.open(file.c_str());
tspCoordFile2.open(file.c_str());

// test file
if(tspCoordFile.fail()){
    cerr << "Error reading file!" << endl;;
    exit(1);
}

// create variables and matrix
int k=0,k2=0;
float x, y, x2, y2;
float** matrix = new float*[countLines(file)];
for(int i = 0; i < countLines(file); ++i)
matrix[i] = new float[countLines(file)];

while(!tspCoordFile.eof()){
    tspCoordFile >> k >> x >> y;

    while(!tspCoordFile2.eof() ){
        tspCoordFile2 >> k2 >> x2 >> y2;

        // calculate distance
        matrix[k][k2]= sqrt(pow(x2-x,2) + pow(y2-y,2));
        cout << matrix[k][k2] << " ";
    }
    cout << " rownumber " << k <<endl;
    tspCoordFile2.clear();
    tspCoordFile2.seekg(0,std::ios::beg);
}
}

The problem I encounter is: unless I add one extra empty line in the coordinate file, my program crashes after printing out 3/4 of the matrix correctly. It does print out the whole matrix just fine when I add this extra line, but it obviously also calculates one extra value, by using the empty line as all 0´s, for each row and one extra row in the end.

  • What its the additional line doing to the program?
  • Why is it stabilizing it?
  • How can I fix it, so that I can calculate a file that has no empty lines?

Thanks in advance.

Fishi
  • 1
  • 1
  • [*Why is iostream::eof inside a loop condition considered wrong?*](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Biffen May 03 '18 at 10:24
  • 1
    Did you step through with your debugger? What did you observe? – nicomp May 03 '18 at 10:33
  • 99.99% of problems with file read on SO are `.eof()` related. There should be a bot for that! – Killzone Kid May 03 '18 at 10:39

0 Answers0