首页 > 解决方案 > 你如何处理未知数量的命令行参数?

问题描述

我正在制作一种以参数为参数的节点客户端:

./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);
    }
}

标签: cnetworkingcommand

解决方案


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

推荐阅读