输出字符的ASCII值 [英] Output ASCII value of character

查看:109
本文介绍了输出字符的ASCII值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

using namespace std;

int main()
{
    char x;
    cout << "enter a character:";
    cin >> x;
    cout << "ASCII Value of " << x << "is" << string(x);
    return 0 ;
}

错误是

main.cpp||In function 'int main()':| 
main.cpp|10|error: invalid conversion from 'char' to 'const char*'| 
main.cpp|10|error:   initializing argument 1 of 'std::basic_string<_CharT, _Traits,_Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]'|
||=== Build finished: 2 errors, 0 warnings ===|

推荐答案

std::cout << "ASCII Value of " << x << "is" << (int)x;

是一种方法(强制转换绕过了I/O流库对char类型的特殊处理),但是这将输出平台的字符编码值,而不必要 ASCII.

is one way (the cast circumvents the special treatement of a char type by the I/O stream library), but this will output your platform's encoded value of the character, which is not necessarily ASCII.

一种便携式解决方案要复杂得多:您需要在128个元素的数组中编码ASCII集,该数组可以存储7位无符号值,然后将x映射到该元素的合适元素.

A portable solution is much more complex: You'll need to encode the ASCII set in a 128 element array of elements capable of storing a 7 bit unsigned value, and map x to a suitable element of that.

这篇关于输出字符的ASCII值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆