如何检查argv [count]是否为整数 [英] How to check if argv[count] is an integer

查看:247
本文介绍了如何检查argv [count]是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C ++创建命令行应用程序,并且我想确保输入是在特定命令参数之后的整数.

I'm trying to create a command line application in C++ and I want to make sure that the input is an integer after a certain command argument.

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

For this example, I want to check if the next argument is an integer after the "-p" command argument. Here's the snippet of my code right now.

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++;
    }
...
}

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

Now this code correctly catches the error in this inputs:

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

但在此输入格式下失败

  • -p 17sss

我试图通过尝试使用sprintf进行比较来对此进行补救.不幸的是,为sprintf提供char数组指针只能在buffer2中输出1个字符.

I tried to remedy this by trying to compare it using sprintf. Unfortunately supplying sprintf with the char array pointer only outputs 1 character in buffer2.

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++;
    }
...
}

有没有办法让sprintf读取整个char数组?如果没有,除了遍历指针直到我打"\ 0"之外,还有更好的解决方案吗?

Is there a way to make sprintf read the whole char array? If not, is there a better solution for this apart from looping through the pointer until I hit "\0"

推荐答案

atoi()无法执行您想要的操作.您需要使用 strtol() 来实现.它具有大大提高的错误检查能力.

atoi() cannot do what you want. You need to use strtol() to achieve this. It has much improved error checking capacity.

签名:

long int strtol(const char *nptr, char **endptr, int base);

此函数以长整型值形式返回转换后的整数,否则返回零值. 转换后,您可以检查endptr的内容并做出决定.

This function returns the converted integral number as a long int value, else zero value is returned. After the conversion, you can check the contents of endptr and decide upon that.

这篇关于如何检查argv [count]是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆