如何正确地将程序参数*char转换为int?

Reb*_*son 3 c pointers casting char

我使用的是Mac OS X 10.6.5,使用XCode 3.2.1 64位来构建一个构建配置为10.6的C命令行工具.调试| x86_64的.我想传递一个正整数作为参数,所以我将argv的索引1作为一个int.这似乎工作,除了似乎我的程序获取ascii值而不是读取整个char数组并转换为int值.当我进入'progname 10'时,它告诉我我已进入49,这是我进入'progname 1'时也得到的.如何让C将整个char数组作为int值读取?谷歌只展示了我(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;
    }

    ...

}
Run Code Online (Sandbox Code Playgroud)

sta*_*ker 14

argv数组中的数字是字符串表示形式.您需要将其转换为整数.

sscanf的

int num;
sscanf (argv[1],"%d",&num);
Run Code Online (Sandbox Code Playgroud)

atoi()(如果有的话)


unw*_*ind 9

转换不能这样做,你需要实际解析文本表示并转换为整数.

这个经典函数被称为atoi(),但也有strtol()甚至sscanf().

  • 不要使用`atoi()`,它可能无法使用它确实**没有**错误检查:http://stackoverflow.com/questions/2729460/usage-of-atoi-in-the- C语言 (3认同)