简体   繁体   中英

ASCII Dec to Char in C++

I want to get every characters of ASCII in normal char. If I only put char key only, it would return dec.

My request:

char alph = //ascii dec to normal char

For example: A in dec is 65 Note: I don't have the characters, but I do have the ASCII codes in dec like 65.

because I need user input like 65

In this case you can do this:

#include <iostream>

using namespace std;

int main() {
    int code;
    cout << "Enter a char code:" << endl;
    cin >> code;

    char char_from_code = code;
    cout << char_from_code << endl;

    return 0;
}

This will ouput:

Enter a char code:
65
A

It seems you have misunderstood the concept.

The numerical value is always there. Whether you print it as the letter or the numerical value depends on how you print.

std::cout will print chars as letters (aka chars) so you'll need to cast it to another integer type to print the value.

char c = 'a';
cout << c << endl;             // Prints a
cout << (uint32_t)c << endl;   // Prints 97

cout << endl;

uint32_t i=98;
cout << i << endl;
cout << (char)i << endl;

Output:

a
97

98
b

This is the method, very simple and then just need to make your own user interface to get input dec

#include <iostream>

using namespace std;

int main() {
    int dec = 65;
    cout << char(dec);
    cin.get();
    return 0;
}

Looks like you need hex/unhex converter. See at boost, or use this bicycle:

vector<unsigned char> dec2bin( const string& _hex )
{
    vector<unsigned char> ret;

    if( _hex.size() < 2 )
    {
        return ret;
    }

    for( size_t i = 0; i <= _hex.size() - 2; i += 2 )
    {
        string two = string( _hex.data() + i, 2 );
        stringstream ss( two );
        string ttt = ss.str();
        int tmp;
        ss >> /*hex >>*/ tmp;
        unsigned char c = (unsigned char)tmp;
        ret.insert( ret.end(), c );
     }

     return ret;
 }

 int main()
 {  
     string a = "65";
     unsigned char c = dec2bin( a )[0];
     cout << (char)c << endl;
     return 0;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM