Signed char question

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>
using namespace std;

int main()
{
signed char 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.
Ok, so how do I store (-1) into a signed char type?
Try declaring it directly:
 
signed char var = -45;


or input the data in an integer and then cast it as a signed char

1
2
3
4
int value;
cin>>value;
signed char output = value;
cout<<output;
With the first option it did not output anything. I don't understand why this is not working.
did you cout<< it? That was just the declaration of the variable. On my compiler it works.
Last edited on
If it doesn't work you can just do this:

1
2
3
int value = -45;
signed char output = value;
cout<<output;


This is the same casting method, but instead of reading int value you just put the value in the declaration.
1
2
3
4
5
6
7
8
9
10
11
12
// Example program
#include <iostream>
#include <string>
using namespace std;

int main()
{
  signed char var = -45;       //declaring signed char directly
  cout << var;                     //this returns a diamond with a question mark in it
  return 0;
}
Last edited on
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>

using namespace std;

int main()
{
  signed char var = -45;       //declaring signed char directly
  cout << static_cast<int>(var);              
  return 0;
}
Last edited on
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.
Last edited on
So you can store a negative value but cannot stream it without a cast?

Correct, you can store any value that can be held by the type, though printing the numerical value will require a cast.

Since character representations are based on the ASCII 8 bit table.

You mean ASCII 7 bit table, right?

Last edited on
You mean ASCII 7 bit table, right?


Yes i meant 7 bit ASCII table.
Topic archived. No new replies allowed.