![](/img/trans.png)
[英]C++ standard alternative to itoa() to convert int to base 10 char*
[英]Unsigned int into a char array. Alternative to itoa?
我对无符号整数有疑问。 我想将我的unsigned int转换为char数组。 为此,我使用itoa。 问题在于itoa可以与int一起正常工作,但不能与unsigned int一起工作(unsigned int被作为普通int继承)。 我应该如何将unsigned int转换为char数组?
在此先感谢您的帮助!
使用stringstream是一种常见方法:
#include<sstream>
...
std::ostringstream oss;
unsigned int u = 598106;
oss << u;
printf("char array=%s\n", oss.str().c_str());
自C ++ 11起更新,有std :: to_string()方法-:
#include<string>
...
unsigned int u = 0xffffffff;
std::string s = std::to_string(u);
您可以简单地使自己的功能像这样:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
unsigned int num,l,i;
cin>>num;
l = log10(num) + 1; // Length of number like if num=123456 then l=6.
char* ans = new char[l+1];
i = l-1;
while(num>0 && i>=0)
{
ans[i--]=(char)(num%10+48);
num/=10;
}
ans[l]='\0';
cout<<ans<<endl;
delete ans;
return 0;
}
您也可以使用sprintf
函数(C语言中的标准功能)
sprintf(str, "%d", a); //a is your number ,str will contain your number as string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.