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;

NASA 的方式:

//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'™ 方式:

//

这样的方式:

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/4629050/

相关文章:

c++ - Visual Studio : E0349 no operator << matches these operands (but no strings in code)

c++ - "fs::path::string"未解析的重载函数类型

c++ - 在集合中使用嵌套类时出现类型不完整错误

c - uPP 设备驱动程序正在从缓冲区中删除数据

html - Copyleft 符号

java - 在Java中如何获取ASCII码的值?

javascript - Unicode字符(向下三 Angular 形)显示为奇怪的文本

c++ - 头文件礼仪

c - 如何检查给定参数是否是另一个给定参数的子字符串

c - mmap 相同的文件,相同的物理内存?