我在使用XCode 3.2.1的64位Mac OS X 10.6.5上構建一個C命令行工具,其編譯配置爲10.6 |調試| x86_64的。我想傳遞一個正整數作爲參數,所以我將argv的索引1作爲一個整型。這似乎工作,除了似乎我的程序獲取ascii值而不是讀取整個字符數組並轉換爲int值。當我輸入'progname 10'時,它告訴我我輸入了49,這也是我輸入'程序名1'時所得到的結果。我如何讓C讀取整個char數組作爲int值?谷歌只顯示我(int)* charPointer,但顯然不起作用。如何正確地將程序參數* char轉換爲int?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(int argc, char **argv) {
char *programName = getProgramName(argv[0]); // gets the name of itself as the executable
if (argc < 2) {
showUsage(programName);
return 0;
}
int theNumber = (int)*argv[1];
printf("Entered [%d]", theNumber); // entering 10 or 1 outputs [49], entering 9 outputs [57]
if (theNumber % 2 != 0 || theNumber < 1) {
showUsage(programName);
return 0;
}
...
}
千萬不要使用`的atoi()`,它可能不可用,它* *沒有任何錯誤檢查:http://stackoverflow.com/questions/2729460/usage-of-atoi-in-the-c-language – 2010-12-01 12:39:22