c++中如何将int转换为char[]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26170523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert int to char[] in c++
提问by john
How could i go about converting 56 and 124 to a character array? I don't understand how you could split up an integer and put it into different parts of a character array. I want to put
我该如何将 56 和 124 转换为字符数组?我不明白如何拆分整数并将其放入字符数组的不同部分。我想放
int num = 56;
into
进入
char num[3]
回答by deKajoo
If your goal is to rewrite itoa here is a well explain implementation of it :
如果您的目标是重写 itoa,这里有一个很好的解释它的实现:
char* itoa(int num, char* str, int base)
{
int i = 0;
bool isNegative = false;
/* Handle 0 explicitely, otherwise empty string is printed for 0 */
if (num == 0)
{
str[i++] = '0';
str[i] = 'std::string numStr = std::to_string(num);
';
return str;
}
// In standard itoa(), negative numbers are handled only with
// base 10. Otherwise numbers are considered unsigned.
if (num < 0 && base == 10)
{
isNegative = true;
num = -num;
}
// Process individual digits
while (num != 0)
{
int rem = num % base;
str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
num = num/base;
}
// If number is negative, append '-'
if (isNegative)
str[i++] = '-';
str[i] = 'std::ostringstream strm;
strm << num;
std::string numStr = strm.str();
'; // Append string terminator
// Reverse the string
reverse(str, i);
return str;
}
回答by Anton Savin
Well, if you want a pure C++ solution, here it is:
好吧,如果你想要一个纯 C++ 解决方案,这里是:
C++11:
C++11:
char * itoa ( int value, char * str, int base );
C++98:
C++98:
##代码##