繁体   English   中英

检查命令行 arguments is not char c++

[英]Check command line arguments is not char c++

我正在尝试检查命令行参数是字母还是数字

int main(int argc, char* argv[])
{
    if(argv[1] is not int) //How does it check if it is number or alphabets
    { 
        cerr<< "arguments must be integer" << endl;
        return -1;
    }
}

如果我在 linux 终端中运行 output 会像

./a.out aasmsnsak
arguments must be integer

使用标准库执行此操作的一种方法是使用<cstdlib>中的strtol 另一个使用istringstream

char *endptr;
const long int argument = strtol (argv[1], &endptr, 10);  // <cstdlib>
if(endptr[0] != '\0') {
    cerr << "arguments must be integer" << endl;
    return -1;
} else if (argument == LONG_MIN || argument == LONG_MAX) {  // <climits>
    // Alternatively you can check for ERANGE in errno
    cerr << "arguments value is out of range" << endl;
    return -1;
} else {
    /* Right type of argument received */
    [..]
}

使用 strtol 的演示

istringstream iss(argv[1]);
int argument;
char more;
if(iss >> argument) {
    if(iss >> more) {
        cerr << p << ": arguments must be integer" << endl;
        return -1;
    } else {
        /* Right type of argument received */
        [..]
    }
} else {
    cerr << p << ": arguments must be integer" << endl;
    return -1;
}

使用 istringstream 的演示

一开始,命令行 arguments 可能存在多个字符。 因此,您将不得不遍历所有这些:

for(char* arg = argv[1]; *arg; ++arg)

现在我假设您要将包含任何非数字字符的字符串分类为非数字,因此在循环内,您将检查每个字符的数字:

if(!isdigit(static_cast<unsigned char>(*arg)))
{
    // non-number-string!

    break; // no need to go on...
}

另一种变体可能只是尝试转换为数字:

std::istringstream s(argv[1]);
int n;
s >> n;
if(s) // number read?
{
    char c;
    s >> c;
    if(!s.eof())
    {
        // not last character reached!
        // -> no number
    }
}

或者:

char* end;
long number = strtol(argv[1], &end, 10);
//                              ^ needed for detecting, if end of string reached
if(*end || errno == ERANGE)
{
    // doesn't point to terminating null character -> no number
    // or number read was out of range
}

C 风格变体:

int n, int l;
if(sscanf(argv[1], "%d%n", &n, &l) == 1 && argv[1][l] == 0)
{
    // successfully scanned an integer and end of string reached -> is a number
}

即使它们不是字母字符,它们也确实总是 char。 您需要做的是尝试将它们解析为正确的数字类型并从那里扣除应用程序 state。

编辑:您可能应该为此使用strol 它不一定是 C++ 但会起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM