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

How do you handle an unknown number of command line arguments?

我正在制作一种接受参数的 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);
    }
}

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

结合使用循环 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.
}