0

I need to read the following kind of file:

dl
format=edgelist1
n=10
data:
1 10 25.8
1 7 53.6
1 3 56.6
2 10 -19.8
2 8 -72.6
2 7 -96.7
2 6 -71.7
2 5 27.1
2 3 2.7
3 9 27.5
3 8 22.5
3 4 -78.2
4 7 5.3
4 6 -41.5
5 10 -61.6
5 9 5.2
5 7 83.8
5 6 -29.5
6 10 -87.4
6 9 -96.0
6 7 78.0
7 10 70.2
8 10 52.0
8 9 8.0

After data:, each line represents a weighted edge.

I am using this loop to read it:

while(u!=0)
{   
    u=0;
    v=0;
    weight=0;
    fscanf(fp,"%d",&u);
    fscanf(fp,"%d",&v);
    fscanf(fp,"%f",&weight);
    fscanf(fp,"\n");
    if (u==0)
    {
        break;
    }
}

It works fine for most graphs. However, in one case I tested, it never leaves the loop.

At first, I thought it was because it wasn't recognizing the floats as it should, but that would mean no graph would be read correctly, as the format is the same.

Furthermore, it successfully read a bunch of connected 1000-vertex graphs. However, it doesn't perform well with one of them. The absurd number of edges makes it impossible for me to analyze edge by edge, so I need help.

erip
  • 16,374
  • 11
  • 66
  • 121
  • Is it for C _or_ C++? Can you also provide the test case where it "_never leaves the loop_"? – Gino Mempin Jun 05 '18 at 23:49
  • @GinoMempin I`m using C++ with included. As I said, the test case is hundreds of edges long – Marcos Martin Jun 06 '18 at 00:14
  • If you're using C++, don't use the C tag. Why are you using C I/O in C++? Try adding a tolerance to the loop condition to make sure it's not floating point error. That if statement is useless by the way. – eesiraed Jun 06 '18 at 00:22
  • Make sure you always check the return value from `fscanf()`. That will tell you whether it made the conversion successfully. Note that the `fscanf(fp, "\n")` line is useless; it reads white space (any white space) until it comes across EOF or a character that isn't white space. If you are typing that by hand, you have to be prescient — knowing what to input next before you get prompted. See also [Trailing white space in `scanf()` format string](http://stackoverflow.com/questions/15740024) — a C question that's relevant. – Jonathan Leffler Jun 06 '18 at 00:48
  • Also, consider reading whole lines and then a single `sscanf()` to parse all the information at once. – Jonathan Leffler Jun 06 '18 at 00:49

1 Answers1

0

Instead of verifying the value of u, check the return value of fscanf:

int u, v;
float weight;
while (fscanf(fp, "%d %d %f", &u, &v, &weight) == 3) {
    // ...
}
O'Neil
  • 3,790
  • 4
  • 16
  • 30