C語言---整型字串轉換

來源:互聯網
上載者:User

標籤:style   http   color   使用   io   strong   檔案   ar   

C語言提供了幾個標準庫函數,能夠將隨意類型(整型、長整型、浮點型等)的數字轉換為字串。下面是用itoa()函數將整數轉 換為字串的一個範例:

    # include <stdio.h>
    # include <stdlib.h>

 

    void main (void)
    {
    int num = 100;
    char str[25];
    itoa(num, str, 10);
    printf("The number ’num’ is %d and the string ’str’ is %s. /n" ,
    num, str);
    }

 

    itoa()函數有3個參數:第一個參數是要轉換的數字,第二個參數是要寫入轉換結果的目標字串,第三個參數是轉移數字時所用 的基數。在上例中,轉換基數為10。10:十進位;2:二進位...
    itoa並非一個標準的C函數,它是Windows特有的,假設要寫跨平台的程式,請用sprintf。
    是Windows平台下擴充的,標準庫中有sprintf,功能比這個更強,使用方法跟printf相似:

 

    char str[255];
    sprintf(str, "%x", 100); //將100轉為16進位表示的字串。

 

 

 

 

函數名: atol

  功 能: 把字串轉換成長整型數

  用 法: long atol(const char *nptr);

  程式例:

#include <stdlib.h>

  #include <stdio.h>

  int main(void)

  {

  long l;

  char *str = "98765432";

  l = atol(str); /* 原來為l = atol(lstr); */

  printf("string = %s integer = %ld/n", str, l);

  return(0);

  }

  atol(將字串轉換成長整型數)

  相關函數 atof,atoi,strtod,strtol,strtoul

  表標頭檔 #include<stdlib.h>

  定義函數 long atol(const char *nptr);

  函數說明 atol()會掃描參數nptr字串,跳過前面的空白字元,直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字串結束時(‘/0‘)才結束轉換,並將結果返回。

  傳回值 返迴轉換後的長整型數。

  附加說明 atol()與使用strtol(nptr,(char**)NULL,10);結果同樣。

  範例 /*將字串a與字串b轉換成數字後相加*/

  #include<stdlib.h>

  main()

  {

  char a[]=”1000000000”;

  char b[]=” 234567890”;

  long c;

  c=atol(a)+atol(b);

  printf(“c=%d/n”,c);

  }

  運行 c=1234567890

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.