這裡的 atoi 或 atol 其實很值得研究, 在 K&R 3.5 節內有程式碼, 以下我用不同寫法,
但觀念完全相同! 請仔細研究它在做啥!!! (K&R 的課本 2.7節也有一個簡易版)
int atoi(char * p) { // 寫 char p[ ] 也可以, 意義完全相同!
int ans=0; // 在 atol( ) 是 long ans=0;
int sign = 1; // assume positive
while( isspace(p[0]) ) ++p; // skip all leading blank 忽略空白
if(p[0] == '-') sign = -1; // 記住是負數啦
if(*p == '-' || *p == '+') ++p; // 跳掉 + - 號
while( isdigit(*p) ) { // *p 與 p[0] 完全相同 !!!
ans = 10*ans + p[0] - '0'; // 算到目前位置的值
++p; // move forward to next char
}
return sign * ans;
} // atoi
這程式內用到了另外兩個 function:
isspace(int) 和 isdigit(int);
它們都是在 <ctype.h> 內宣告的,
但因傳回是 int,
所以不宣告在 C也沒問題,
但在 C++ 則一定要 #include <ctype.h> 或是 #include <cctype>
該兩個 Library function 其實也很簡單, 自己寫就可以了:
int isdigit(int x) {
return (x >= '0' && x <='9'); // '0' .. '9' 就是 48 .. 57 ASCII
}
int isspace(int x) { // white space(廣義空白)請參看 K&R 第二章2.3節
if(x==' ' || x == '\t' || x == '\v') return 1; //space,水平,垂直TAB
if(x=='\n' || x == '\r' || x == '\f') return 1; //LF, CR, Form Feed
return 0;
}
試著自己把自己當電腦, 分析上面程式,
例如若 kk = atoi(" 13849haha"); 會怎樣?
其實 isdigit(int) 也可以這樣寫:
int isdigit(int x) { // 注意參數是 int; char 也是一種 int
if(x >= '0' && x <='9') return 1; // 不要錯寫成 & 喔!
return 0; // 不必寫 else, 因前面狀況已經 return 了
}
*** 寫出 atof(char*) 的程式碼或是寫出研究 atof(char*) 的心得
請思考 double atof(char*) 這function 要怎麼寫?
注意要能算出 x=atof("135.246"); x=atof(" -38.49"); x=atof(" +49.38"); 等!
想一想: 如果用到 x = atof(" -250.375ABCDE"); 會怎樣?
想懂要如何寫後請把程式碼寫在下方:
但若想半小時候仍不知道怎麼寫的, 請參看 K&R第四章 4.2節的 atof(char*) 範例,
看懂後寫出心得, 至少 125 字 !
Ans: