Standard Input for Unsigned Character

喜夏-厌秋 提交于 2019-12-03 01:21:56

问题


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'.


回答1:


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;
}



回答2:


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';


来源:https://stackoverflow.com/questions/25087533/standard-input-for-unsigned-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!