ASCII Dec to Char in C++

ASCII Dec to Char in C++

本文关键字:in C++ Char to Dec ASCII      更新时间:2023-10-16

我想用普通字符获取ASCII的每个字符。如果我只放char key,它会返回 dec。

我的要求:

char alph = //ascii dec to normal char

例如:十进制中的 A 为 65注意:我没有字符,但我确实有 dec 中的 ASCII 代码,例如 65。

因为我需要像 65 这样的用户输入

在这种情况下,您可以执行以下操作:

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

这将输出:

Enter a char code:
65
A

看来你误解了这个概念。

数值始终存在。是将其打印为字母还是数值取决于您的打印方式。

std::cout 会将字符打印为字母(又名字符),因此您需要将其转换为另一个整数类型才能打印值。

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;

输出:

a
97
98
b

这是方法,非常简单,然后只需要制作自己的用户界面即可获得输入dec

#include <iostream>
using namespace std;
int main() {
    int dec = 65;
    cout << char(dec);
    cin.get();
    return 0;
}

看起来你需要十六进制/十六进制转换器。请参阅助力,或使用这辆自行车:

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