我在使用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