1. atof(將字串轉換成浮點型數)
相關函數
atoi,atol,strtod,strtol,strtoul
表標頭檔
#include <stdlib.h>
定義函數
double atof(const char *nptr);
函數說明
atof()會掃描參數nptr字串,跳過前面的空白字元,直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字串結束時('\0')才結束轉換,並將結果返回。參數nptr字串可包含加號或減號、小數點或E(e)來表示指數部分,如123.456或123e-2。
傳回值
返迴轉換後的浮點型數。
附加說明
atof()與使用strtod(nptr,(char**)NULL)結果相同。
範例
/* 將字串a 與字串b轉換成數字後相加*/
#include <stdio.h> #include <stdlib.h> main() { char *a="-100.23"; char *b="200e-2"; float c; c=atof(a)+atof(b); printf("c=%.2f\n",c); }
2.atoi(將字串轉換成整型數)
相關函數:
atof,atol,atrtod,strtol,strtoul
表標頭檔:
#include<stdlib.h>
定義函數:
int atoi(const char *nptr);
函數說明:
atoi()會掃描參數nptr字串,跳過前面的空白字元,直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字串結束時('\0')才結束轉換,並將結果返回。
傳回值:
返迴轉換後的整型數。
附加說明:
atoi()與使用strtol(nptr,(char**)NULL,10);結果相同。
範例:
/* 將字串a 與字串b轉換成數字後相加*/
#include <stdio.h> #include <stdlib.h> main() { char a[]="100"; char b[]="256"; int c; c=atoi(a)+atoi(b); printf("c=%d\n",c); }