问题
I just want to write a simple text file:
ofstream test;
test.clear();
test.open("test.txt",ios::out);
float var = 132.26;
BYTE var2[2];
var2[0] = 45;
var2[1] = 55;
test << var << (BYTE)var2[0] << (BYTE)var2[1];
test.close();
But in the output file I get:
132.26-7
I don't get what the problem is...
回答1:
BYTE is nothing but an alias for unsigned char. By default, when you output a char in a stream, it is converted to its ASCII character. In the ASCII table, the character 45 is '-' and the character 55 is '7'.
Try this instead:
test << var << (int)var2[0] << (int)var2[1];
回答2:
I think that the problem might be that BYTE type might be a typedef for char. If this were the case, then whenevernyou try to write out a BYTE to a stream, it will print the ASCII character corresponding to that byte rather than the numeric value of the byte. Notice that the characters - and 7 correspond to ASCII values 45 and 55, for example.
To fix this, you'll want to do two things:
- Typecast the BYTEs you're writing to some integral type like int or short before writing them to the file. This forces the stream to write a numeric value rather than a character.
- Output some amount of whitespace in-between all of the data you output. Right now everythingnis bleeding together because there are no spaces, which makes things harder to read.
Hope this helps!
来源:https://stackoverflow.com/questions/5147337/writing-multiple-variable-types-to-a-text-file-using-ofstream