C當中有一些函數專門用於把字符串形式轉換成數值形式。
printf()函數和sprintf()函數 -->通過轉換說明吧數字從數字形式轉換為字符串形式;
scanf()函數把輸入字符串轉換為數值形式;
應用場景:
編寫程序需要使用數值命令形參,但是命令形參被讀取為字符串。要使用數值必須先把字符串轉換為數字。
atoi()函數:
int atoi(char *str);
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int main(void) 5 { 6 int i,times; 7 8 if(argc < 2 || times = atoi(argv[1])<1) 9 printf("Usage:%s positive-number\n",argv[0]); 10 else 11 for(i=0;i<times;i++) 12 puts("Hello,good looking!"); 13 14 return 0; 15 }
程序運行示例:
$ hello 3
Hello, good looking!
Hello, good looking!
Hello, good looking!
作用就是根據參數,選擇打印幾次Hello, good looking!
如果參數開頭是非數字字符,則atoi函數返回值是0;因為這種行為是未定義的。因此需要有錯誤檢測功能的strtol()函數會更安全。
stdlib.h頭文件:不僅包含atoi()函數,還包含了atof()函數、atol()函數;
atof()函數把字符串轉換成double類型的值;
atol()函數把字符串轉換成long類型的值;
++++++++++++++++++++++++++++++++++++++++++++++++++++++
strtol函數原型:long strtol(const char * restrict nptr,char ** restrict endptr, int base);
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define LIM 30 4 char * s_gets(char * st, int n); 5 6 7 int main(void) 8 { 9 char number[LIM]; 10 char * end; 11 long value; 12 13 puts("Enter a number (empty line to quit);"); 14 while(s_gets(number,LIM)&& number[0] !='\0') 15 { 16 value =strtol(number,&end,10); 17 printf("base 10 input,base 10 output:%ld,stopped at %s (%d)\n",value,end, *end); 18 value = strtol(number, &end, 16); 19 printf("base 16 input,base 10 output:%ld,stopped at %s (%d)\n",value,end, *end); 20 puts("Next number:"); 21 } 22 puts("Bye!\n"); 23 return 0; 24 } 25 26 char * s_gets(char * st, int n) 27 { 28 char * ret_val; 29 int i=0; 30 31 ret_val = fgets(st, n, stdin); //讀取成功,返回一個指針,指向輸入字符串的首字符; 32 if(ret_val) 33 { 34 while(st[i]!='\n' && st[i]!='\0') 35 i++; 36 if(st[i] =='\n') //fgets會把換行符也吃進來了,fgets會在末尾自動加上\0; 37 st[i]='\0'; 38 else //其實是'\0' 39 while(getchar() != '\n') //會把緩沖區后續的字符都清空 40 continue; 41 } 42 return ret_val; 43 }
程序運行:
Enter a number (empty line to quit);
10
base 10 input,base 10 output:10,stopped at (0)
base 16 input,base 10 output:16,stopped at (0)
Next number:
10atom
base 10 input,base 10 output:10,stopped at atom (97)
base 16 input,base 10 output:266,stopped at tom (116)
Next number: