Q: How can I input and output a negative character value. I know there are three types of character values: char, unsigned char (0 to 255), and signed char (-128 to 127)?
1 2 3 4 5 6 7 8 9 10 11 12 13
//When I input (-1), I only get the '-' sign returned.
#include <iostream>
usingnamespace std;
int main()
{
signedchar val;
cout <<"Enter a negative value.\n";
cin >>val;
cout <<val; //returns '-' only
return 0;
}
The extraction operator extracts one character at a time into a char, signed char, or unsigned char. So in this case you get the '-' character, the remaining characters, the '1' and the end of line character, are left in the input buffer for the next extraction operation.
// Example program
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
signedchar var = -45; //declaring signed char directly
cout << var; //this returns a diamond with a question mark in it
return 0;
}
Yes the insertion operator much like the extraction operator operate on character representations not their numerical values when dealing with the char type. If you want to print the numerical value you need to cast that value to an int.
1 2 3 4 5 6 7 8 9 10
#include <iostream>
usingnamespace std;
int main()
{
signedchar var = -45; //declaring signed char directly
cout << static_cast<int>(var);
return 0;
}
Ahhh, thank you. I am reading a book about char types and how they can store various ranges. I was wanting to test that by just declaring a signed char variable with a negative value.
So you can store a negative value but cannot stream it without a cast? Since character representations are based on the ASCII 7 bit table.