如何正确调用getopt函数 [英] How to call correctly getopt function
本文介绍了如何正确调用getopt函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从 http://code.google.com/p/darungrim/source/browse/trunk/ExtLib/XGetopt.cpp?r=17
`check.cpp: In function ‘int main()’:`
check.cpp:14:55:错误:从'const char **'到'char * const *'的无效转换[-fpermissive]
/usr/include/getopt.h:152:12:error:初始化int getopt(int,char * const *,const char *)的参数2 '[-fpermissive]
#include <iostream>
#include <cstring>
#include <string>
#ifdef USE_UNISTD
#include <unistd.h>
#else
#include "XGetopt.h"
#endif
using namespace std;
int main() {
string text="-f input.gmn -output.jpg";
int argc=text.length();
cout<<"argc: "<<argc<<endl;
char const * argv = text.c_str();
cout<<"argv: "<<argv<<endl;
int c = getopt (argc, &argv, "f:s:o:pw:h:z:t:d:a:b:?");
cout<<"c: "<<c<<endl;
return 0;
}
推荐答案
:
- 参数列表不是字符串。它是一个字符串列表。不要被shell或其他程序要求参数列表作为单个字符串混淆。在一天结束时,这些程序会将一个字符串拆分成参数数组,并运行一个可执行文件(参见 execv )。
- 在参数列表中始终有一个隐含的第一个参数,它是一个程序名称。
- Argument list is not a string. It is a list of strings. Don't get confused by shell or other programs that ask for a list of arguments as a single string. At the end of day, those programs would split a string into arrays of arguments and run an executable (see execv, for example).
- There is always an implicit first argument in argument list that is a program name.
这是您的代码,修正:
#include <string>
#include <iostream>
#include <unistd.h>
int main()
{
const char *argv[] = { "ProgramNameHere",
"-f", "input.gmn", "-output.jpg" };
int argc = sizeof(argv) / sizeof(argv[0]);
std::cout << "argc: " << argc << std::endl;
for (int i = 0; i < argc; ++i)
std::cout << "argv: "<< argv[i] << std::endl;
int c;
while ((c = getopt(argc, (char **)argv, "f:s:o:pw:h:z:t:d:a:b:?")) != -1) {
std::cout << "Option: " << (char)c;
if (optarg)
std::cout << ", argument: " << optarg;
std::cout << '\n';
}
}
这篇关于如何正确调用getopt函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文