1、itoa()函數(整型轉字元)
以下是用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:二進制...
2、atoi()函數(字元轉整型)
頭檔案:#include <stdlib.h>
atoi() 函數用來将字元串轉換成整數(int),其原型為:
int atoi (const char * str);
【函數說明】atoi() 函數會掃描參數 str 字元串,跳過前面的空白字元(例如空格,tab縮進等,可以通過
isspace()函數來檢測),直到遇上數字或正負符号才開始做轉換,而再遇到非數字或字元串結束時('\0')才結束轉換,并将結果傳回。
【傳回值】傳回轉換後的整型數;如果 str 不能轉換成 int 或者 str 為空字元串,那麼将傳回 0。
範例:将字元串a 與字元串b 轉換成數字後相加。
純文字複制- #include <stdio.h>
- #include <stdlib.h>
- int main ()
- int i;
- char buffer[256];
- printf ("Enter a number: ");
- fgets (buffer, 256, stdin);
- i = atoi (buffer);
- printf ("The value entered is %d.", i);
- system("pause");
- return 0;
執行結果:
Enter a number: 233cyuyan
The value entered is 233.