在C++中,optarg
是一个C风格字符串,用于存储getopt()
函数解析命令行参数时找到的选项参数值。要将optarg
作为C++字符串对象获取,可以使用std::string
类型进行转换。
以下是一个简单的示例:
#include<iostream>
#include<string>
#include <cstring>
#include <unistd.h>
int main(int argc, char *argv[]) {
int c;
std::string optarg_str;
while ((c = getopt(argc, argv, "s:")) != -1) {
switch (c) {
case 's':
optarg_str = std::string(optarg);
std::cout << "Option -s has argument: "<< optarg_str<< std::endl;
break;
default:
abort();
}
}
return 0;
}
在这个示例中,我们使用getopt()
函数解析命令行参数,并在找到选项-s
时将optarg
转换为std::string
类型的optarg_str
。这样,我们就可以方便地使用C++字符串对象进行后续操作。
领取专属 10元无门槛券
手把手带您无忧上云