The biggest problem you are having is you are not controlling your read-loop with the return of the read itself. For example, in your case you would want:
int i = 0;
while (fscanf(myFile, "%1d%1d", &wt[i],&val[i]) == 2)
i++;
At the end of your read, i
would hold the number of elements read into your arrays.
(note: you cannot use any input function correctly unless you check the return...)
Instead of reading the values into separate arrays, whenever you are coordinating multiple values as a single object (e.g. each val
and wt
pair), you should be thinking struct
. That allows you to coordinate both values as a single object.
A simple example in your case could be:
#include <stdio.h>
#define MAXVAL 20 /* if you need a constant, #define one (or more) */
typedef struct { /* struct with int val, wt + typdef for conveninece */
int val, wt;
} mydata;
int main (int argc, char **argv) {
size_t n = 0; /* number of elements read */
mydata arr[MAXVAL] = {{ .val = 0 }}; /* array of mydtata */
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
/* read all pairs of values in file into array */
while (fscanf (fp, "%d %d", &arr[n].val, &arr[n].wt) == 2)
n++;
if (fp != stdin) /* close file if not stdin */
fclose (fp);
for (size_t i = 0; i < n; i++) /* output values */
printf ("arr[%zu] %2d %2d\n", i, arr[i].val, arr[i].wt);
}
Above, the code does the same as I suggested in conditioning the read-loop on successfully reading a pair of values from the file. The only difference is that is coordinates the val
and wt
values in a struct.
Example Use/Output
With your data in the file dat/val_wt.txt
, you would receive the following output:
$ ./bin/read_val_wt dat/val_wt.txt
arr[0] 3 25
arr[1] 2 20
arr[2] 1 15
arr[3] 4 40
arr[4] 5 50
While above we read directly with fscanf
, you can make your read a bit more robust by reading each line into a character array first, and then parsing the wanted values from the character array with sscanf
. You are essentially doing the same thing, but by using fgets/sscanf
you can make an independent validation of (1) the read of the line; and (2) the parse of the wanted information from the line. If you have a malformed-line, it prevents the matching-failure from impacting the read of the remaining lines in the input file.
Look things over and let me know if you have further questions.