简体   繁体   中英

Reading numbers from a file to store in a two-dimensional array in C

I'm trying to read from a file that looks like this

1 1 756.00
1 2 996.45
1 3 5159.14
1 4 710.21
1 5 10.00
2 1 1449.00
2 2 416.10
2 3 3119.48
2 4 2130.63
2 5 0.00
3 2 810.30
3 3 2219.63
3 4 1151.03
3 5 0.00
4 1 1071.00
4 3 1319.78
4 4 1861.24
4 5 0.00

And then storing the numbers into a two dimensional array. The file, however, is also about 478 lines. This because I'm supposed to keep storing the current value, plus the value being read in every time it iterates. I don't know how to approach this at all. I've tried doing this

 while(!feof(fp)) 
 {
    for(i = 0; i < 4; i++) 
    {
       fgets(buffer, 100, fp);
       sscanf(buffer, "%d", &i);

       for(j = 0; j < 5; j++) 
       {
           fgets(buffer, 100, fp);
           sscanf(buffer, "%d", &j);

           for(k = 0.0; k != ' '; k++) 
           {
               fgets(buffer, 100, fp);
               sscanf(buffer, "%lf", &value);
               sales[i-1][j-1] +=value;
           }
       }
    }
 }

fclose(fp);

But I'm pretty sure this isn't even the correct way to go about it. I just need at least some guidance in the right direction, please.

It looks like the first and second values are the indexes. If so then this may work.

while ( fgets(buffer, 100, fp)) {
    if ( ( sscanf(buffer, "%d%d%lf", &i, &j, &value)) == 3) {
        sales[i-1][j-1] =value;
    }
}

What about:

while(scanf("%d %d %lf", &r, &c, &v) != EOF)
    sales[r-1][c-1] += v;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM