我正在制作一种接受参数的 Node 客户端:
./node <port> <address> <neighbourAddress>:<weight>
我已经处理了端口和地址,并通过atoi将它们的值存储在它们各自的变量中。但是,我不知道如何处理
<neighbourAddress>:<weight>
因为它们可以重复出现。例如
./node 8888 1 26:2 34:3 12:8
在这种情况下,它出现了三次,但不仅限于那个次数。 我需要做什么才能读取由“:”分隔的参数并将它们的值存储在变量中?
这是我目前所拥有的:
#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);
}
}
最佳答案
将循环与 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.
}
关于c - 你如何处理未知数量的命令行参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55594782/