I've been looking for similar problems but am still unable to find a solution to my problem.
I am taking a text file and converting it to a binary file to be used in another program. The other program compiles and outputs everything just fine but the problem seems to lay in my file conversion.
void makefile( ifstream & fi, ofstream & fo ){
struct{
int acct;
char name[25];
float dolr;
} x;
int i;
char line[81], *p, *q;
while ( fi.getline( line, 81 ) ) {
x.acct = atoi( line );
p = line;
while ( *p++ != ' ' );
for ( q = x.name, i = 24 ; i-- ; ){
*q++ = *p++; // *q = '\0';
}
while ( *--q == ' ' ); // find end of string
*++q = '\0'; // mark end of name string
x.dolr = atof(p);
fo.write( (char*)&x, sizeof(x) );
}
}
The input text file looks like this...
000027183 Hun, Attila The 1234.56
000012345 Dooright, Dudley 211.22
000031416 Whiplash, Snidely 1200.00
000014142 Jekyll, Doctor 1500.00
000031623 Hyde, Mister 1500.00
000010203 Bear, Smokey The 2000.00
000020103 Dumpty, Humpty 3000.00
000030102 Woman, Wonder 3824.36
000030201 Hulnk, Incredible 9646.75
000022345 Snowman, Abominable 2496.24
When I run the program and I check the binary (using a separate program) I can see the converted file but it looks like this:
27183 Hun, Attila The 1234.56 0.00
12345 Dooright, Dudley 211.22 0.00
31416 Whiplash, Snidely 1200.0 0.00
14142 Jekyll, Doctor 1500.00 0.00
31623 Hyde, Mister 1500.00 0.00
10203 Bear, Smokey The 2000.00 0.00
20103 Dumpty, Humpty 3000.00 0.00
30102 Woman, Wonder 3824.36 0.00
30201 Hulnk, Incredible 9646.7 5.00
22345 Snowman, Abominable 2496 0.24
This was originally written in C and I'm beginning to wonder if that reflects in the code that my professor has given us to make the binary file. Any suggestions?
Update: This is the the function in the other program that reads the file to "check it"
void
chkfile( ifstream & f ){
struct {
int acct;
char name[25];
float dolr;
} x;
while ( f.read( (char *)&x, sizeof(x) ) ){
cout << setfill('0') << setw(9) << x.acct << " ";
cout.setf( ios::left, ios::adjustfield );
cout << setfill(' ') << setw(26) << x.name;
cout.setf( ios::right, ios::adjustfield );
cout.setf( ios::fixed, ios::floatfield );
cout.setf( ios::showpoint );
cout.precision(2);
cout << setw(10) << x.dolr << '\n';
}
}
UPDATE: Turns out the problem was not in the code but in the text file used to create the binary file. I was using tabs to space between names and amounts so the parsing was off when converting to binary. I used blank spaces and that solved my problem!