C語言中一些將字符串轉(zhuǎn)換為數(shù)字的函數(shù)小結(jié)
C語言atoi()函數(shù):將字符串轉(zhuǎn)換成int(整數(shù))
頭文件:
#include <stdlib.h>
atoi() 函數(shù)用來將字符串轉(zhuǎn)換成整數(shù)(int),其原型為:
int atoi (const char * str);
【函數(shù)說明】atoi() 函數(shù)會掃描參數(shù) str 字符串,跳過前面的空白字符(例如空格,tab縮進等,可以通過 isspace() 函數(shù)來檢測),直到遇上數(shù)字或正負符號才開始做轉(zhuǎn)換,而再遇到非數(shù)字或字符串結(jié)束時('\0')才結(jié)束轉(zhuǎn)換,并將結(jié)果返回。
【返回值】返回轉(zhuǎn)換后的整型數(shù);如果 str 不能轉(zhuǎn)換成 int 或者 str 為空字符串,那么將返回 0。
范例:將字符串a(chǎn) 與字符串b 轉(zhuǎn)換成數(shù)字后相加。
#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; }
執(zhí)行結(jié)果:
Enter a number: 233cyuyan The value entered is 233.
C語言atof()函數(shù):將字符串轉(zhuǎn)換為double(雙精度浮點數(shù))
頭文件:
#include <stdlib.h>
atol() 函數(shù)的名字源于“ascii to long”,用來將字符串轉(zhuǎn)換成長整型數(shù)(long),其原型為:
long atol(const char * str);
【函數(shù)說明】atol() 會掃描參數(shù) str 字符串,跳過前面的空白字符(例如空格,tab縮進等,可以通過 isspace() 函數(shù)來檢測),直到遇上數(shù)字或正負符號才開始做轉(zhuǎn)換,而再遇到非數(shù)字或字符串結(jié)束時('\0')才結(jié)束轉(zhuǎn)換,并將結(jié)果返回。
【返回值】返回轉(zhuǎn)換后的長整型數(shù)(long);如果 str 不能轉(zhuǎn)換成 long 或者 str 為空字符串,那么將返回 0。
示例:將輸入的字符串轉(zhuǎn)換成long。
#include <stdio.h> #include <stdlib.h> int main () { long int li; char buffer[256]; printf ("Enter a long number: "); fgets(buffer, 256, stdin); li = atol(buffer); printf ("The value entered is %ld.\n", li); system("pause"); return 0; }
執(zhí)行結(jié)果:
Enter a long number: 1200cyuyan The value entered is 1200.
C語言atof()函數(shù):將字符串轉(zhuǎn)換為double(雙精度浮點數(shù))
頭文件:
#include <stdlib.h>
函數(shù) atof() 用于將字符串轉(zhuǎn)換為雙精度浮點數(shù)(double),其原型為:
double atof (const char* str);
atof() 的名字來源于 ascii to floating point numbers 的縮寫,它會掃描參數(shù)str字符串,跳過前面的空白字符(例如空格,tab縮進等,可以通過 isspace() 函數(shù)來檢測),直到遇上數(shù)字或正負符號才開始做轉(zhuǎn)換,而再遇到非數(shù)字或字符串結(jié)束時('\0')才結(jié)束轉(zhuǎn)換,并將結(jié)果返回。參數(shù)str 字符串可包含正負號、小數(shù)點或E(e)來表示指數(shù)部分,如123. 456 或123e-2。
【返回值】返回轉(zhuǎn)換后的浮點數(shù);如果字符串 str 不能被轉(zhuǎn)換為 double,那么返回 0.0。
溫馨提示:ANSI C 規(guī)范定義了 stof()、atoi()、atol()、strtod()、strtol()、strtoul() 共6個可以將字符串轉(zhuǎn)換為數(shù)字的函數(shù),大家可以對比學習;使用 atof() 與使用 strtod(str, NULL) 結(jié)果相同。另外在 C99 / C++11 規(guī)范中又新增了5個函數(shù),分別是 atoll()、strtof()、strtold()、strtoll()、strtoull(),在此不做介紹,請大家自行學習。
范例:
#include <stdio.h> #include <stdlib.h> int main(){ char *a = "-100.23", *b = "200e-2", *c = "341", *d = "100.34cyuyan", *e = "cyuyan"; printf("a = %.2f\n", atof(a)); printf("b = %.2f\n", atof(b)); printf("c = %.2f\n", atof(c)); printf("d = %.2f\n", atof(d)); printf("e = %.2f\n", atof(e)); system("pause"); return 0; }
執(zhí)行結(jié)果:
a = -100.23 b = 2.00 c = 341.00 d = 100.34 e = 0.00
相關(guān)文章
C語言詳解關(guān)鍵字sizeof與unsigned及signed的用法
這篇文章主要為大家詳細介紹了C語言關(guān)鍵字sizeof&&unsigned&&signed,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-06-06