摘:C語言數字轉換為字串

來源:互聯網
上載者:User

數字轉換為字串

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

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

void main (void);
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。

下列函數可以將整數轉換為字串:
----------------------------------------------------------
函數名 作 用
----------------------------------------------------------
itoa() 將整型值轉換為字串
itoa() 將長整型值轉換為字串
ultoa() 將無符號長整型值轉換為字串
----------------------------------------------------------
請注意,上述函數與ANSI標準是不相容的。能將整數轉換為字串而且與ANSI標準相容的方法是使用sprintf()函數,請看下例:
#include<stdio.h>
# include <stdlib. h>

void main (void);
void main (void)
{
int num = 100;
char str[25];
sprintf(str, " %d" , num);
printf ("The number 'num' is %d and the string 'str' is %s. \n" ,
num, str);

}

在將浮點型數字轉換為字串時,需要使用另外一組函數。以下是用fcvt()函數將浮點型值轉換為字串的一個例子:

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

void main (void);
void main (void)
{
double num = 12345.678;
char * sir;
int dec_pl, sign, ndigits = 3; /* Keep 3 digits of precision. * /
str = fcvt(num, ndigits, &dec-pl, &sign); /* Convert the float
to a string. * /
printf("Original number; %f\n" , num) ; /* Print the original
floating-point
value. * /
printf ("Converted string; %s\n",str); /* Print the converted
string's value. * /
printf ("Decimal place: %d\n" , dec-pi) ; /* Print the location of
the decimal point. * /
printf ("Sign: %d\n" , sign) ; /* Print the sign.
0 = positive,
1 = negative. * /
}

fcvt()函數和itoa()函數有數大的差別。fcvt()函數有4個參數:第一個參數是要轉換的浮點型值;第二個參數是轉換結果中十進位小數點右側的位元;第三個參數是指向一個整數的指標,該整數用來返迴轉換結果中十進位小數點的位置;第四個參數也是指向一個整數的指標,該整數用來返迴轉換結果的符號(0對應於正值,1對應於負值)。
需要注意的是,fcvt()函數的轉換結果中並不真正包含十進位小數點,為此,fcvt()函數返回在轉換結果中十進位小數點應該佔據的位置。在上例中,整型變數dec_pl的結果值為5,因為在轉換結果中十進位小數點應該位於第5位後面。如果你要求轉換結果中包含十進位小數點,你可以使用gcvt()函數(見下表)。

下列函數可以將浮點型值轉換為字串:
-------------------------------------------------------------------------
函數名 作 用
-------------------------------------------------------------------------
ecvt() 將雙精確度浮點型值轉換為字串,轉換結果中不包含十進位小數點
fcvt() 以指定位元為轉換精度,餘同ecvt()
gcvt() 將雙精確度浮點型值轉換為字串,轉換結果中包含十進位小數點
-------------------------------------------------------------------------

 

聯繫我們

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