C++ 如何在c++;
如何将56和124转换为字符数组?我不明白你怎么能把一个整数拆分成一个字符数组的不同部分。 我想把C++ 如何在c++;,c++,char,int,C++,Char,Int,如何将56和124转换为字符数组?我不明白你怎么能把一个整数拆分成一个字符数组的不同部分。 我想把 int num = 56; 进入 如果要将整数转换为表示该整数的以null结尾的字符串,请使用 char * itoa ( int value, char * str, int base ); 如果您的目标是重写itoa,这里有一个很好的解释它的实现: char* itoa(int num, char* str, int base) { int i = 0; bool isN
int num = 56;
进入
如果要将整数转换为表示该整数的以null结尾的字符串,请使用
char * itoa ( int value, char * str, int base );
如果您的目标是重写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] = '\0';
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] = '\0'; // Append string terminator
// Reverse the string
reverse(str, i);
return str;
}
char*itoa(int-num,char*str,int-base)
{
int i=0;
bool为阴性=假;
/*显式处理0,否则为0打印空字符串*/
如果(num==0)
{
str[i++]='0';
str[i]='\0';
返回str;
}
//在标准itoa()中,负数只能用
//以10为基数。否则,数字将被视为无符号。
如果(num<0&&base==10)
{
isNegative=true;
num=-num;
}
//处理单个数字
while(num!=0)
{
int rem=基数的num%;
str[i++]=(rem>9)?(rem-10)+'a':rem+'0';
num=num/基;
}
//如果数字为负数,则附加“-”
如果(为负)
str[i++]='-';
str[i]='\0';//追加字符串终止符
//把绳子倒过来
反向(str,i);
返回str;
}
<>代码>嗯,如果你想要一个纯C++的解决方案,这里是:
C++11:
std::string numStr = std::to_string(num);
C++98:
std::ostringstream strm;
strm << num;
std::string numStr = strm.str();
std::ostringstream strm;
你的意思是要取一个整数(56)并将其转换为包含“5”和“6”的字符[2]?请提供更多细节。是的,这就是我试图做的。关于sprintf(buff,“%d”,num)呢代码>?这是C的更多方式,那么C++ +约翰<代码> char num(3)< /C>比C++更为C。任务可能是将整数的字节复制到char
数组中。另外,由于问题被标记为C++,所以你不妨使用<代码> STD::toSype(value)。ItoA是坏的,因为它可能对所有的都不起作用。systems@john给我一个系统,它不会工作从网上阅读它不保证工作,这种声明是没有上下文无用的。如果itoa
不起作用,它就不会在语言标准库中。
std::ostringstream strm;
strm << num;
std::string numStr = strm.str();