I am trying to read strings from a file and convert them to integers for storage in a struct. The strtol() function works well but removes any 0s from the start of the tokens. Is there any way I can keep them? The input file is formatted like the example below.
003345.755653
000046.003265
073532.003434
122280.065431
Input file ^^^
struct store{
int *age;
int *ref;
}rec[20];
char *token;
char*ptr;
while (!feof (filea)){
fgets(buffer, sizeof buffer, filea);
token = strtok(buffer, ".");
rec[count].age = malloc(10);
rec[count].age = strtol(token, &ptr, 10);
printf("Age: %i\n", rec[count].age);
token = strtok(NULL, ".");
rec[count].ref = malloc(10);
rec[count].ref = strtol(token, &ptr, 10);
printf("Ref: %i\n\n", rec[count].ref);
count++;
}
Once your string has been converted to an
int
or any other numeric type, all its leading zeros are gone, because they do not change the value of an integer.You can add back leading zeros to get your numbers all have the same number of digits, but matching the exact number of leading zeros from a file would require additional storage.
Here is how you can format all your integers to two digits, with zero padding if necessary:
Note: Your program has multiple errors. You need to fix them before it starts working properly.
age
andref
as pointers, but you use them like scalar variablesage
andref
usingmalloc
, and then you override it with a numeric valueptr
after the read. You should use it to see if anything has been read from the file.The compiler must have issued multiple warnings related to the issues described above. It is a good idea to treat all compiler warnings as errors, because it helps you find simple problems like these.