【发布时间】:2010-12-01 12:34:19
【问题描述】:
我在 Mac OS X 10.6.5 上使用 XCode 3.2.1 64 位构建 C 命令行工具,构建配置为 10.6 |调试 | x86_64。我想传递一个正偶整数作为参数,所以我将 argv 的索引 1 转换为 int。这似乎可行,但似乎我的程序正在获取 ascii 值而不是读取整个 char 数组并转换为 int 值。当我输入“progname 10”时,它告诉我输入了 49,这也是我输入“progname 1”时得到的结果。如何让 C 将整个 char 数组作为 int 值读取? Google 只向我展示了 (int)*charPointer,但显然这不起作用。
#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;
}
...
}
【问题讨论】: