C++ getopt
2020-09-15 16:40 宋海宾 阅读(483) 评论(0) 收藏 举报在unistd.h 头文件中,获取参数
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
int main(int argc, char *argv[])
{
int index;
char ch;
while((ch = getopt(argc, argv, "dt:")) != EOF)
{
switch(ch)
{
case 'd':
puts("enter d");
break;
case 't':
puts("enter t");
printf("optarg value is %s\n", optarg);
break;
default:
return 1;
}
}
argc -= optind;
argv += optind;
for(index = 0; index < argc; index++)
{
puts(argv[index]);
}
return 0;
}
简析一下这个程序的主要功能:
getopt(argc, argv,"dt:"))
他完成的意思是表示程序有一个-d和一个-t选项,但是你看-t后面还有一个冒号,表示-t参数后面,要跟着一个参数。
在-t参数被捕获的时候,则可以:
printf("optargvalue is %s\n", optarg);
这么样,用来得到-t后面的那个参数(其实是紧跟-t后面的字符串)
最末尾有两行这样的代码:
-
argc -= optind;
-
argv += optind;
他表示跳过已经读取的参数,比如跳过了-d、-t和-t后面的那个字符串
浙公网安备 33010602011771号