下面的程序?qū)⒆址D(zhuǎn)換為long,但根據(jù)我的理解,它也會返回錯誤。我依賴的事實是,如果strtol將字符串成功轉(zhuǎn)換為long,那么第二個參數(shù)strtol應(yīng)該等于NULL。當我用55運行以下應(yīng)用程序時,我收到以下消息。./convertToLong 55Could not convert 55 to long and leftover string is: 55 as long is 55如何成功檢測strtol的錯誤?在我的應(yīng)用程序中,零是有效值。碼:#include <stdio.h>#include <stdlib.h>static long parseLong(const char * str);int main(int argc, char ** argv){ printf("%s as long is %ld\n", argv[1], parseLong(argv[1])); return 0; }static long parseLong(const char * str){ long _val = 0; char * temp; _val = strtol(str, &temp, 0); if(temp != '\0') printf("Could not convert %s to long and leftover string is: %s", str, temp); return _val;}
3 回答

躍然一笑
TA貢獻1826條經(jīng)驗 獲得超6個贊
你錯過了一個間接層。您想要檢查字符是否是終止字符NUL,而不是指針是否NULL:
if (*temp != '\0')
順便說一下,這不是一個錯誤檢查的好方法。strto*通過將輸出指針與字符串的結(jié)尾進行比較,不能完成函數(shù)族的正確錯誤檢查方法。它應(yīng)該通過檢查零返回值并獲得返回值來完成errno。
- 3 回答
- 0 關(guān)注
- 1233 瀏覽
添加回答
舉報
0/150
提交
取消