Ive written two functions that read lines from a .txt document with posts like the one below. "Number of loans" is only written once.
Number of loans: 1
Loan number: 1
Sum: 200.000000
year: 2011
Interest: 20.000000
Installment: 1000.000000
Payed off: 2012
Description: 12
What the program reads:
Loan number: 1
Sum: 200.000000
year: 2011000000
Interest: 20.000000
Installment: 1000.000000
Payed off:
Description: 12
'Payed off' doesnt work because it's calculated based on the 'year' value
The code i have written is:
void readFile( int * nLoans, loan ** memory, FILE * streamPointer ){
int i, k, d;
char buf[MAXLINELENGTH+1];
*nLoans = readLine( STARTNUMBEROFLOANES, MAXLINELENGTH, streamPointer );
(*memory) = calloc(*nLoans, sizeof(loan));
for( i = 0; i < *nLoans; i++ ){
(*memory)[i].loanID = (int)readLine( STARTLOANID, MAXLINELENGTH, streamPointer );
(*memory)[i].sum = readLine( STARTOFVALUES, MAXLINELENGTH, streamPointer );
(*memory)[i].year = (int)readLine( STARTOFVALUES, MAXLINELENGTH, streamPointer );
(*memory)[i].interest = readLine( STARTOFVALUES, MAXLINELENGTH, streamPointer );
(*memory)[i].installment = readLine( STARTOFVALUES, MAXLINELENGTH, streamPointer );
fgets( buf, MAXLINELENGTH, streamPointer);
d = strlen(buf);
for( k = 0; k < (d - 1 - STARTOFVALUES ); k++ ){
((*memory)[i].yearPayedOff)[k] = buf[k + STARTOFVALUES];
}
((*memory)[i].yearPayedOff)[d] = '\0';
fgets( buf, MAXLINELENGTH, streamPointer );
d = strlen(buf);
for( k = 0; k < (d - STARTOFVALUES - 1) ; k++ ){
((*memory)[i].description)[k] = buf[k+ STARTOFVALUES ];
}
((*memory)[i].description)[d] = '\0';
fgets( buf, 2, streamPointer );
}
}
and:
double readLine( int indexFirstNumber, int alowedLineLength, FILE * streamPointer ){
char line[alowedLineLength + 1], numberString[ (int)log(MAXALOWEDLOANSUM) ];
double returnNumber = 0;
int i = indexFirstNumber;
fgets( line, (alowedLineLength+1), streamPointer );
printf("\n%s", line);
while( line[i] != '\n' && line[i] != ' ' && line[i] != '\0'){
numberString[i-indexFirstNumber] = line[i];
i++;
}
numberString[i] = '\0';
printf("\n%s", numberString);
if( !(sscanf(numberString, "%lf", &returnNumber) == 1) ){ printf("\nError reading from file\n"); }
return returnNumber;
}
The error, that the program adds lots of zeros to the value in the file, occurs between the two printf() statements in readLine()