Zahid Faizal
2007-08-03 14:56:27 UTC
All this time I mindlessly thought that unsigned char is just like
other unsigned members of the integer family (integer, short, long,
long long) with a more constrained range of values ---- from 0 to
255. That is what I had read somewhere. Imagine my surprise when I
realized that the way unsigned char is read from stdin or a file is
completely different from other entities in the integer family! I did
not expect that in the case of unsigned char, the value that would be
assigned to a variable would be its ASCII equivalent. I knew that
this is the behavior for char, but I did not expect unsigned char to
do that. I was badly bitten by this revelation today.
Kindly see the source snippet below, where I was able to recreate the
problem. MY APOLOGIES TO comp.lang.c READERS THAT THIS SAMPLE IS C++,
but the issue that I am describing pertains to C as well.
Thanks,
Zahid
////////////////////////
#include <iostream>
using namespace std;
int
main()
{
unsigned char first;
unsigned short second;
unsigned int firstInt, secondInt;
cout << "\nEnter first value: ";
cin >> first;
firstInt = first;
cout << "\nEnter second value: ";
cin >> second;
secondInt = second;
cout << "Your values are " << firstInt << " and " << secondInt <<
endl;
}
////////////////////////
I entered 0 and 0 and the output was as follows:
Your values are 48 and 0
other unsigned members of the integer family (integer, short, long,
long long) with a more constrained range of values ---- from 0 to
255. That is what I had read somewhere. Imagine my surprise when I
realized that the way unsigned char is read from stdin or a file is
completely different from other entities in the integer family! I did
not expect that in the case of unsigned char, the value that would be
assigned to a variable would be its ASCII equivalent. I knew that
this is the behavior for char, but I did not expect unsigned char to
do that. I was badly bitten by this revelation today.
Kindly see the source snippet below, where I was able to recreate the
problem. MY APOLOGIES TO comp.lang.c READERS THAT THIS SAMPLE IS C++,
but the issue that I am describing pertains to C as well.
Thanks,
Zahid
////////////////////////
#include <iostream>
using namespace std;
int
main()
{
unsigned char first;
unsigned short second;
unsigned int firstInt, secondInt;
cout << "\nEnter first value: ";
cin >> first;
firstInt = first;
cout << "\nEnter second value: ";
cin >> second;
secondInt = second;
cout << "Your values are " << firstInt << " and " << secondInt <<
endl;
}
////////////////////////
I entered 0 and 0 and the output was as follows:
Your values are 48 and 0