Amit Upadhyay Amit Upadhyay - 3 years ago 82
C++ Question

leading 0's are not getting read from file

I am reading the content of a file character by character:

The file has:

000001111100000


When I use this code to read

int content;// converting to char will result in proper output.
std::ifstream fin;
fin.open("zero_one");
fin>>content;
while (!fin.eof())
{
std::cout<<content;
fin>>content;
}
fin.close();


I get the output as:
1111100000
(the leading zeros are not present) but the trailing zeros are present.

The concern is: as I am using
>>
operator to read then, why don't I get the leading zeros in output whereas as I get the trailing zeros in output.

Also, If I convert the
int
to
char
for
content
variable then the output is same as the content of the file. Why is this so? As far as I know, the only difference between the
char
and
int
is the size in bytes of the variable.

Answer Source

If content is an int, it reads the data as a single integer: you get an int with the value 1111100000. If content is a char, it reads each character separately.

You can see the difference if, in the while loop, you say std::cout<<content<<'\n'; instead of just std::cout<<content;. Then if content is an int you will see one line containing 1111100000, but if it’s a char you will see 15 lines, one for each character of input.

If you put spaces between each character of the input file, they would be read as separate ints and the results would be the same, but there would still be an important difference: the values of the chars aren’t char(0) and char(1), but '0' and '1' (0x30 and 0x31, respectively), the ASCII values of the corresponding digits. The ints on the other hand would actually be 0 or 1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download