Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2D arrays and reading from a txt file

Status
Not open for further replies.

robinsql

Programmer
Aug 2, 2002
236
IE
I have just begun to program in C and am trying to write a currency conversion program. I need to populate a 2D array using the values read in from a text file, rates.txt.
The rates are
1
0.99
0.64
121.42
4.65
I assume I must use floating point arrays.
How should I read the values in from the file?
Should I read them directly into the array or into five seperate variables and then produce my 2D array from these five variables?
Or should I read from the file into a 1D array and then produce my 2D array from each member of this array?
I need some guidance as to the best possible method and any help would be gratefully received. Thanks
 
There's all kinds of ways to do this.

I think the simplest is probably not worrying about
a conversion till you populate the array.

Simple working code here:
Code:
#include <stdio.h>
#include <stdlib.h>



int main(int argc, char **argv) {
int s = 0, x;
float *farr = NULL;
char buf[50];
FILE *fd;
    
      if (argc == 2) {
         farr = malloc(50 * sizeof(float));
         if ( (fd = fopen(argv[1],&quot;r&quot;)) != NULL) {
              while ( (fgets(buf,50,fd)) != NULL) {
                      farr[s] = (float)atof(buf);
                      /*printf(&quot;Read %f\n&quot;, farr[s]);*/
                        if (s >= 50) {
                           realloc(farr,(s * sizeof(float)));
                       }
               s++;
               }
              fclose(fd);
          } else {
            printf(&quot;Error opening file: %s\n&quot;, argv[1]);
            return 1;
          }
      } else {
          printf(&quot;You must give the filename as the first argument\n&quot;);
          return 1;
      }
     
      for (x=0 ; x < s ; x++) {
          printf(&quot;%f\n&quot;, farr[x]);
      }
      free(farr);
return 0;
}
 
Thanks for your help marsd. I have found a slightly different way of doing it as I don't completely understanad your code as I am a complete beginner.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top