Hugh Buelow
Member
Hopefully one more question for me for the time being
I have to design and create a class that will act as a buffer before outputting to the user. I have to overload the << operator and store the values that were to be displayed in that buffer then do calculations that will count how many characters are to the right of the << and get the arithmetic sum to become the "checkSum". However, I have a problem with overloading<< with int variables. Here's my code:
And the main will consist of:
The line should give a count of 14, I think.
However, the problem I have is that it makes the i1 variable (with the value of 45) back to the ASCII character "-". I know it has to do with the casting of int i to a char but that's the only way I found to change the 'z' back from ASCII value 122 to "z" (and only one character count) and to detect endl characters as only one character.
Anyone know how I can fix this?
A char really is an signed integer, 8 bit in size, with values ranging from -128 to 127. In C (and by extension in C++), a char has no special meaning: it's just a small number.
In the C++ stream library, a char DO have a special meaning:
- a "char *" value will be rendered as a string of bytes
- a "char" value will be rendered as a single byte
In your code, two things are happening. First, you force an integer value into a char, that you feed to the stream. The stream won't see a number, because to it, a char is special and must be treated as a raw byte. This is why you see a '-' instead of 45, because in ASCII, the character 45 is '-'.
Second, since you don't have an overloaded operator<< for "char", it will use the closest match: the operator<<(int); remember, a char is really just a small integer.
What you should do instead is to add an overload for operator<<(char) and remove the cast in the operator<<(int).