-2

I am trying to send unsigned characters through a program, and I would like to be able to get the numbers through standard input (ie std::cin). For example when I type 2 I would like it send ☻ (unsigned char 2). when I use the code:

 std::cout << "Enter values: ";
            {
                unsigned char d;
                unsigned char e = 2;
                std::cin >> d;
                WriteFile(file, &d, 1, &written, NULL);
                std::cout << "d= " << d << "\n"; 
                std::cout << "e= " << e;
            }

I get

 Enter values: 2
 d=2
 e=☻

Can anyone tell me why d is being interpreted Incorrectly as unsigned char 50 while e is being interpreted correctly as unsigned char 2?

And of course after your explanation can You explain how to get User input and convert it so that I send 2 rather than '2'.

jeffpkamp
  • 2,732
  • 2
  • 27
  • 51

2 Answers2

3

Because std::cin >> d; reads by default a char type, so the input 2 translates into the character 2 (with ASCII code 50) and not the character represented by the ASCII code 2. This is a normal behaviour, otherwise trying to read numbers from cin will end up being a mess.

On the other hand, in unsigned char e = 2; you explicitly assign a value (2) to the variable, so the compiler blindly assigns it to e.

You probably want this:

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
    string myString;
    cin >> myString;
    char c = atoi(myString.c_str());
    cout << c << endl;
}
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • okay, I figured as much. So how can I get the ascii value 2 from a console input without using alt+2? – jeffpkamp Aug 01 '14 at 19:48
  • @jeffpkamp You don't. It's not a printable character. – Bart van Nierop Aug 01 '14 at 19:50
  • @jeffpkamp I believe the standard says that `std::cin` is text-mode, so I do not think you can read ascii directly. I am not sure though. What you can do is to read it as a number, then convert the character that represents the number into an integer. Can use for example `char c = atoi(myString.c_str())` to convert a previously read string `myString` into an integer. See the code I just posted above. – vsoftco Aug 01 '14 at 19:52
  • Why go through `std::string`, instead of going through `int`? This seems needlessly complicated. – hyde Aug 02 '22 at 09:55
0

When you enter 2 via std::cin, it's correctly interpreted as the character literal '2'.

You should replace

unsigned char e = 2;

with

unsigned char e = '2';
maxdefolsch
  • 179
  • 5