c - 你如何处理未知数量的命令行参数?
问题描述
我正在制作一种以参数为参数的节点客户端:
./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);
}
}
解决方案
结合使用循环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.
}
推荐阅读
- css - 背景图片在手机上不正确
- apache-spark - 是否需要在 Spark 中广播对象成员?
- python - 如何使用不重复的 Pymongo 将文档(MongoDB)插入到集合中
- android - Crashlytics 正在向 Fabric 报告,但 Firebase Crashlytics 中没有可用的跟踪信息
- c++ - QTcpSocket 客户端如何理解它在队列中?(并且不会进入连接状态)
- database - 如何使用 LARAVEL 控制器以 JSON 格式保存数组数据
- amazon-web-services - 向 Slack 发送 SNS 通知
- c++ - 当派生类的基类具有成员指针时深复制派生类
- java - 如何以编程方式获取授权 cookie?
- math - 如何根据样本获得标准差