Standard Input for Unsigned Character

前端 未结 2 2045
灰色年华
灰色年华 2021-01-29 14:53

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 woul

相关标签:
2条回答
  • 2021-01-29 15:01

    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;
    }
    
    0 讨论(0)
  • 2021-01-29 15:15

    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';
    
    0 讨论(0)
提交回复
热议问题