c++ - 将 int 转换为 ASCII 字符

标签 c++ c ascii

我有

int i = 6;

我想要

char c = '6'

通过转换。有什么简单的建议吗?

编辑: 我还需要生成一个随机数,并转换为一个字符,然后添加一个“.txt”并在 ifstream 中访问它。

最佳答案

直接的方式:

char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char aChar = digits[i];

更安全的方式:

char aChar = '0' + i;

通用方式:

itoa(i, ...)

方便的方法:

sprintf(myString, "%d", i)

C++ 方式:(取自 Dave18 的回答)

std::ostringstream oss;
oss << 6;

老板方式:

Joe, write me an int to char converter

学霸方式:

char aChar = '6';

乔的方式:

char aChar = '6'; //int i = 6;

美国宇航局的方式:

//Waiting for reply from satellite...

外星人的方式:“9”

//Greetings.

上帝的方式:

Bruh I built this

小飞侠的方式:

char aChar;

switch (i)
{
  case 0:
    aChar = '0';
    break;
  case 1:
    aChar = '1';
    break;
  case 2:
    aChar = '2';
    break;
  case 3:
    aChar = '3';
    break;
  case 4:
    aChar = '4';
    break;
  case 5:
    aChar = '5';
    break;
  case 6:
    aChar = '6';
    break;
  case 7:
    aChar = '7';
    break;
  case 8:
    aChar = '8';
    break;
  case 9:
    aChar = '9';
    break;
  default:
    aChar = '?';
    break;
}

圣诞老人的方式:

//Wait till Christmas!
sleep(457347347);

重力方式:

//What

'6'( Jersey )Mikes'™ 方式:

//

SO 方式:

Guys, how do I avoid reading beginner's guide to C++?

我的方式:

or the highway.

评论:我已经添加了 Handy 方式和 C++ 方式(以拥有一个完整的集合)并将其保存为一个 wiki。

编辑:满意吗?

关于c++ - 将 int 转换为 ASCII 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57928046/

相关文章:

c++ - 指向类创建错误核心转储的指针

c - libcurl 中的内存泄漏

python - (ctypes)msvcrt.printf 并在 python 中打印

java - 使用 ascii 编码而不是字符实体对 xml 进行编码

php - 使用一个函数将 ASCII 和 UTF-8 转换为非特殊字符

css - AsciiEffect.js && CSS3DRenderer.js 兼容吗?三.js/WebGL

c++ - 我需要使用整数作为对象

c++ - 在 OpenGL 中使用等 ionic 分形生成地形

c++ - 为 C++ 示例设置基本 Esent

c - 我正在尝试打印日历,但无法对齐结果