Reputation: 129
I am new to C++ and coming from a C# / Java background I feel like I am kind of spoilt.
What I am trying to achieve here is to get the data input by the user as byte (unsigned char
) using cin
.
#include <iostream>
using namespace std;
typedef unsigned char byte;
int main()
{
byte num = 0;
char exitKey = '0';
cout << "Type in a number between 0 and 255.\n";
cin >> num;
cout << "\nYour number multiplied by 2 is:\n" << (num * 2);
cin >> exitKey;
return 0;
}
The value returned is the ASCII decimal value of the character I typed in. How can I get the actual value, treating the value as a number?
Help is appreciated. Thanks.
Upvotes: 0
Views: 1400
Reputation: 409176
It doesn't matter what type-aliases you use, when reading using cin >>
a character is always a character, and will be read as a character.
The value you are getting is the ASCII code for the character '1'
.
If you want to read it as a number, then use a proper numeric datatype, like int
.
Upvotes: 3
Reputation: 779
Since you are using char datatype here. The 1 value entered here is considered as character and ASCII value of 1 (49) is getting stored and 49 * 2 = 98 is getting printed. Instead of char use int as datatype.
Upvotes: 2