将 int 转换为 ASCII 字符 [英] Convert an int to ASCII character
问题描述
我有
int i = 6;
我想要
char c = '6'
通过转换.有什么简单的建议方法吗?
by conversion. Any simple way to suggest?
我还需要生成一个随机数,并转换为字符,然后添加一个.txt"并在 ifstream 中访问它.
also i need to generate a random number, and convert to a char, then add a '.txt' and access it in an 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 的回答)
C++ way: (taken from Dave18 answer)
std::ostringstream oss;
oss << 6;
老板方式:
Joe,给我写一个 int 到 char 的转换器
Joe, write me an int to char converter
Studbos 方式:
char aChar = '6';
char aChar = '6';
乔的方式:
char aChar = '6';//int i = 6;
char aChar = '6'; //int i = 6;
美国宇航局的方式:
//等待卫星回复...
//Waiting for reply from satellite...
外星人的方式:'9'
//您好.
上帝的方式:
Bruh 我建了这个
彼得潘的方式:
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);
重力方式:
//什么
'6' (Jersey) Mikes'™ 方式:
//
所以方式:
伙计们,我该如何避免阅读C++ 初学者指南?
Guys, how do I avoid reading beginner's guide to C++?
我的方式:
或高速公路.
评论:我添加了 Handy 方式和 C++ 方式(以获得完整的集合),并将其保存为 wiki.
Comment: I've added Handy way and C++ way (to have a complete collection) and I'm saving this as a wiki.
满意?
这篇关于将 int 转换为 ASCII 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!