如何错误处理命令行参数?

问题描述 投票:0回答:1

我正在尝试使用这样的函数来错误处理命令行参数:

int check(char *r){
    int arg, valid = 0;
    for (int i = 0; i<sizeof(*r); i++){
        if(!isdigit(r[i]))
            valid = 0;
        else if (atoi(r)<1)
            valid = 0;
        else
            valid = 1;
    }
    if (valid == 1)
        arg = atoi(r);
    while(valid == 0){
        cout<<"Input was wrong! Please input a positive integer greater than 0: ";
        cin>>arg;
        if (arg<1 || cin.fail()){
            cin.clear();
            cin.ignore(1000, '\n');
            valid = 0;
        }
        else
            valid = 1;
    }
    return arg;
}

int main(int argc, char const *argv[]){
  int player;
  int row;
  int col;

  for (int i = 1; i<7; i+=2){
    if(argv[i][0] == '-' && argv[i][1] == 'p'){
        player = check( argv[i+1] );
    }
    else if (argv[i][0] == '-' && argv[i][1] == 'r'){
        row = check( argv[i+1] );
    }
    else if (argv[i][0] == '-' && argv[i][1] == 'c'){
        col = check( argv[i+1] );
    }
    else
        cout<<"Enter -p <number of players> -r <number of rows> -c <number of columns> "<<endl;
  }
}

但是它不会编译,表示没有匹配的函数调用来检查。用户应输入的示例是“ ./a.out -p 2 -r 6 -c 7”。检查用户是否仅在命令行中输入正整数的最佳方法是什么?

编译器在编译时输出以下消息。

    main.cpp:41:15: error: no matching function for call to
      'check'
            player = check( argv[i+1] );
                     ^~~~~
main.cpp:8:5: note: candidate function not viable: 1st
      argument ('const char *') would lose const qualifier
int check(char *r){
    ^
main.cpp:44:12: error: no matching function for call to
      'check'
            row = check( argv[i+1] );
                  ^~~~~
main.cpp:8:5: note: candidate function not viable: 1st
      argument ('const char *') would lose const qualifier
int check(char *r){
    ^
main.cpp:47:12: error: no matching function for call to
      'check'
            col = check( argv[i+1] );
                  ^~~~~
main.cpp:8:5: note: candidate function not viable: 1st
      argument ('const char *') would lose const qualifier
int check(char *r){
c++ function error-handling command-line-arguments
1个回答
2
投票

[char const*char*是无效的转换,您需要从char const *argv[]中删除const

int main(int argc, char *argv[])
© www.soinside.com 2019 - 2024. All rights reserved.