Programing in C...any erros here?

Permabanned
Joined
14 Jul 2005
Posts
2,051
Location
Portishead, Bristol
A mate is totaly stucj on this and i have no idea...anyone here?

It should be reading in a date in dd/mm/yyyy format, then an amount of cash (its based on a basic bank statement). However it outputs the date with "04" stuck on the end of every year (so we're apparently in the year 200704

i = 0;
while (fgets (line, LINESIZE, ifp) != NULL)
{
strncpy(temp, &line[0], 2);
x = atoi(temp);
t.day = x;
x = 0;
printf("Transaction %i: %d/", i, t.day);

strncpy(temp, &line[3], 2);
x = atoi(temp);
t.month = x;
x = 0;
printf("%d/", t.month);

strncpy(temp2, &line[6], 4);
x = atoi(temp2);
t.year = x;
x = 0;
printf("%d ", t.year);

strncpy(temp2, &line[11], 100);
x = atoi(temp2);
t.transaction_amount = x;
x = 0;
printf("%.2f \n", t.transaction_amount);

i++;
}
 
strncpy copies at MOST the number of characters you specify, it doesn't null-terminate unless the null character is within the character limit that you specify in the call to strncpy.

When you do "strncpy(temp2, &line[11], 100);" near the end of the loop, temp2 is ending up with a value like "123.04", the rest of the characters being null. The next iteration of the loop, you read the year - "strncpy(temp2, &line[6], 4); " which is setting temp2 to "200704" (not setting a null, because you specified 4 characters).

You can either put the nulls in yourself, which is easy for the fixed-sized strings like the year -

Code:
strncpy(temp2, &line[6], 4);
temp2[4] = 0;
x = atoi(temp2);

for the variable sized field like the transaction amount, easiest would be just to initialize the variable first with nulls -

Code:
memset(temp2, 0, sizeof(temp2)); // substitute the max string size, if its not a char array
strncpy(temp2, &line[11], 100);
x = atoi(temp2); 
...
 
Last edited:
Back
Top Bottom