如何检查argv [count]是否为整数

MDu*_*Duh 5 c printf pointers

我正在尝试用C++创建一个命令行应用程序,我想确保在某个命令参数之后输入是一个整数.

对于此示例,我想检查下一个参数是否是"-p"命令参数后面的整数.这是我现在代码的片段.

while (count < argc){
    if (strcmp("-p", argv[count]) == 0){
        has_p = true; //Boolean
        pid = atoi(argv[count + 1]);
        if (pid == 0 && argv[count + 1] != "0" ){
            err = 1;
            cout << "pid argument is not a valid input" << endl;
            pid = -1;
        }
        count++;
    }
...
}
Run Code Online (Sandbox Code Playgroud)

现在,此代码正确捕获此输入中的错误:

  • -p 1777
  • -p sss
  • -p sss17
  • -p [空格] -U

但是输入格式失败了

  • -p 17sss

我尝试通过使用sprintf进行比较来解决这个问题.不幸的是,使用char数组指针提供sprintf只会在buffer2中输出1个字符.

while (count < argc){
    if (strcmp("-p", argv[count]) == 0){
        has_p = true; //Boolean
        pid = atoi(argv[count + 1]);
        sprintf(buffer, "%d", pid);
        sprintf(buffer2, "%d", *argv[count + 1]);
        if (pid == 0 && argv[count + 1] != "0" || (buffer != buffer2) ){
            err = 1;
            cout << "pid argument is not a valid input" << endl;
            pid = -1;
        }
        count++;
    }
...
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让sprintf读取整个char数组?如果没有,除了循环指针直到我点击"\ 0"之外,是否有更好的解决方案

Nat*_*tta 13

atoi()不能做你想要的.你需要用来strtol()实现这一目标.它有很多改进的错误检查能力.

签名:

long int strtol(const char *nptr, char **endptr, int base);
Run Code Online (Sandbox Code Playgroud)

此函数将转换后的整数作为long int值返回,否则返回零值.转换后,您可以检查内容endptr 并做出决定.

  • @ANjaNA - 不,您不能使用返回值来确定转换是否失败,因为转换失败时的返回值也可能是转换成功的结果.你**必须**使用`endptr`的值. (2认同)