stof()、atoi()、atol()、strtod()、strtol()、strtoul() 共6個可以將字串轉換為數字的函式
阿新 • • 發佈:2018-11-16
標頭檔案:#include <stdlib.h>
atoi() 函式用來將字串轉換成整數(int),其原型為:
int atoi (const char * str);
【函式說明】atoi() 函式會掃描引數 str 字串,跳過前面的空白字元(例如空格,tab縮排等,可以通過 isspace() 函式來檢測),直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字串結束時('\0')才結束轉換,並將結果返回。
【返回值】返回轉換後的整型數;如果 str 不能轉換成 int 或者 str 為空字串,那麼將返回 0。
溫馨提示:ANSI C 規範定義了 stof()
範例:將字串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.