简体   繁体   中英

Writing multiple variable types to a text file using ofstream

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...

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:

  1. 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.
  2. 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!

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM