I'm trying to write a program that reads a file, prints what's in the file, add the contents of said file to an array, print from the array and then write to a file using the contents of the array.
My problem is when I try and print to the file, the array only prints the last entry in my char* array. Why does this happen?
Here's the problem code:
char name[100];
int age = 0;
float bBalance = 0;
char* namesArray[100];
int ageArray[100];
float floatArray[100];
for (int i = 0; i < 100; ++i)
{
namesArray[i] = (char*)malloc(100);
}
fptr = fopen("NTD.txt", "r");
int lPtr = 1;
if (fptr == NULL)
{
exit(1);
}
else
{
while (fscanf(fptr, "%99[^ ,], %d, %f", name, &age, &bBalance) != EOF)
{
namesArray[lPtr] = name;
ageArray[lPtr] = age;
floatArray[lPtr] = bBalance;
printf("%s \n", namesArray[lPtr]);
printf("%d \n", ageArray[lPtr]);
printf("%f \n", floatArray[lPtr]);
lPtr++;
}
fclose(fptr);
}
fptr = fopen("writeTo.txt", "w");
if (fptr == NULL)
{
exit(1);
}
else
{
int i = 1;
while (lPtr != 0)
{
fprintf(fptr, "%s,%d,%f \n",namesArray[i], ageArray[i], floatArray[i]);
i++;
}
fclose(fptr);
}
This is what the final file should look like:
Jane,50,420.69
Sam,20,50.00
Fabian,21,682.22
Zac,35,40000.00
Gabe,12,0.00
Shy,29,12.00
Charlot,99,0.00
Gen,15,64592.68
Guy,98,20000.00
Bill,60,1000000.00
This is what it actually looks like:
Bill,50,420.690002
Bill,20,50.000000
Bill,21,682.219971
Bill,35,40000.000000
Bill,12,0.000000
Bill,29,12.000000
Bill,99,0.000000
Bill,15,64592.679688
Bill,98,20000.000000
Bill,60,1000000.000000
If you need anything else, please let me know