c++ 中使整型轉換成字元型

來源:互聯網
上載者:User

 

在java裡面,整數可以很方便地轉換成字串.
只要寫成:
byte/short/int a = (範圍內的數值);
String str = ""+ a;
System.out.println(str);

這樣就解決了

但是C++ 裡面的 string 並不支援這樣的轉換
將一個整數int a,轉換成字串呢?
在晚上搜到的解決方式是

長整形 long :
#include <stdlib.h>

char   *ltoa(long   value,   char   *string,   int   radix)
將長整形數轉換為等價的字串
value   轉換的長整形數,radix   數制(如10表示十進位)
string   轉換後的字串

例如
long lo = 34567754433l;
char* cha= new char[64];
 ltoa(lo,cha,10);

運行到這裡,cha的結構就變成了內容看起來是 lo 的字串了

整形 int:
#include <stdlib.h>
char   *itoa(int   value,   char   *string,   int   radix)
將整形數value轉換為其等價的字串
string   轉換後的字串

與long 相同用法

然後用string

這裡只是提出想象的步驟,實際應用的時候可以計算好了int 的位元,然後建立與整數位元相等長度 加一或加二 的字元數組

PS:因為字串以'\0'結尾,所以最後一位要留著並賦予成結尾的字元,長度+1

PS2: 如果是負數要在最前面留一個位置放置加號或減號 '-' 長度+1

另外:如果使用VC2008 使用了 itoa 命令,編譯器會警告

warning C4996: 'itoa': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _itoa. See online help for details.

大意是不贊成使用 itoa, 因為可能因移植而造成名字衝突之類

最後放上網上找到的類比 itoa 的代碼

//// *==============================================================================

////     功能:  實現整型到字串的轉化
////     參數說明: int  nValue  [in]: 需要轉化的整數值
////    char* szString [out]: 轉化字串結果
////    int  radix  [in]: 基數(進位)
////     傳回值: 轉化結果的指標
////  補充:  經過測試,發現這個函數有缺陷:認不出負數..........
////------------------------------------------------------------------------------

//     IFLYTEK_Embeded   :   sszhou   :   create   :   2004-01-30
===============================================================================*/

char*   IFLY_itoa(int   nValue,   char   *szString,   int   radix)
{
 int   i=0,   Len=0;
 int   nTemp=nValue;
 char   *lpString=szString;

 /*   獲得符號   */
 if(nValue <0)
 {
  lpString[0]   =   '- ';
  lpString++;
  nTemp   *=   -1;
 }

 /*   倒序錄入szString   */
 for(i=0;   nTemp   !=   0   ;   i++)
 {
  lpString[i]   =   nTemp%radix;
  /*   進行數值向符號的轉化   */
  if(lpString[i] <=9)
  {
   lpString[i]   +=   0x30;
  }
  else
  {
   lpString[i]   +=   0x37;
  }
  nTemp   /=   radix;
 }

 /*   解決0的問題   */
 if(i==0)
 {
  lpString[0]   =   0x30;
  i++;
 }

 /*   獲得正確的順序   */
 Len   =   i;
 for(i=0;   i   <   (Len/2);   i++)  
 {
  nTemp   =   lpString[i];
  lpString[i]   =   lpString[Len-i-1];
  lpString[Len-i-1]   =   nTemp;
 }

 lpString[Len]   =0;
 

 return   szString;
};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.