您如何处理未知数量的命令行参数?

时间:2019-04-09 14:06:12

标签: c networking command

我正在制作一种类型为参数的Node客户端:

./node <port> <address> <neighbourAddress>:<weight> 

我已经处理了端口和地址,并通过atoi将它们的值存储在各自的变量中。但是,我不知道如何处理

<neighbourAddress>:<weight> 

,因为它们可以重复出现。例如

./node 8888 1 26:2 34:3 12:8

在这种情况下,它出现3次,但不仅限于此数量。 为了读取以':'分隔的参数并将它们的值存储在变量中,该怎么办?

这是我到目前为止所拥有的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "print_lib.h"

int port;
int ownAddress;

int main(int argc, char *argv[]){

    if(argc >= 3){

        /* to receive port number */
        port = atoi(argv[1]);
        if((port <= 1024 || port >= 65535) && port != 0){
            fprintf(stderr, "Port number has to be between 1024 and 65535.\n");
            exit(EXIT_FAILURE);
        }

        /* to receive ownaddress */
        ownAddress = atoi(argv[2]);
        if(ownAddress >= 1024 && ownAddress != 0){
            fprintf(stderr, "Node's address has to be less than 1024.\n");
            exit(EXIT_FAILURE);
        }

        /* below here is where I need to handle reoccuring arguments */
        /* in the format <neighbourAddress>:<weight> */

    }
    else {
        fprintf(stderr, "Too few arguments\n");
        exit(EXIT_FAILURE);
    }
}

2 个答案:

答案 0 :(得分:2)

结合使用循环和sscanf

for (int i = 3; i < argc; i++) {
    int addr, weight;
    if (sscanf(argv[i], "%d:%d", &addr, &weight) != 2) ERROR();
    // use values here, e.g. assign them into an array.
}

答案 1 :(得分:1)

使用argc获取输入参数的数量,减去:程序名称,端口,地址,然后剩下<neighbourAddress>:<weight>输入的数量,然后就可以循环遍历它们。即<neighbourAddress>:<weight>的数量是argc - 3