程序是这样工作的,参数在开始时以这样的形式提供:
-w cat
字符串“cat”存储在变量 中图案以及后面跟着 的每个字母- 我们做某事;在这种情况下,我们设置 mode = W。我遇到的问题是当参数采用以下形式时:
-w -s -n3,4 cat
现在我相信和以前一样模式按读取顺序设置为 W、S 和 N。如果我想存储/记住字母的顺序模式设置为循环完成后,我可以将信息存储在数组中。也应该做图案被分配了字符串“cat”。如果我错了,请纠正我,或者有更简单的方法来做到这一点。
其次,我希望能够访问和存储数字 3 和 4。我不确定这是如何完成的,也不确定是什么 argc -= optind;和
argv += optind;做。除了我认为参数存储在字符串数组中。
enum MODE {
W,S,N
} mode = W;
int c;
while ((c = getopt(argc, argv, ":wsn")) != -1) {
switch (c) {
case 'w':
mode = W;
break;
case 's':
mode = S;
break;
case 'n':
mode = N;
break;
}
}
argc -= optind;
argv += optind;
string pattern = argv[0];
更新:弄清楚如何访问这些数字,我只需要看看循环期间 argv 中的内容。所以我想我只会将我在那里找到的值存储在另一个变量中以供使用。
最佳答案
getopt
设置全局变量 optarg
当提供了带值的参数时。例如:
for(;;)
{
switch(getopt(argc, argv, "ab:h")) // note the colon (:) to indicate that 'b' has a parameter and is not a switch
{
case 'a':
printf("switch 'a' specified\n");
continue;
case 'b':
printf("parameter 'b' specified with the value %s\n", optarg);
continue;
case '?':
case 'h':
default :
printf("Help/Usage Example\n");
break;
case -1:
break;
}
break;
}
见 here一个更完整的例子。
I want to be able to access and store the numbers 3 and 4.
由于这是一个逗号分隔的列表,您需要解析
optarg
对于 token (请参阅 strtok
),然后使用 atoi
或类似的将每个转换为整数。
关于c++ - 在 C++ 中使用 getopt() 处理参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52467531/