簡體   English   中英

將unsigned int轉換為char數組。 替代itoa?

[英]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);

您可以簡單地使自己的功能像這樣:

使用OWN功能在Ideone上進行代碼鏈接

    #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

使用Sprintf在Ideone上進行代碼鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM