如何正确调用getopt函数 [英] How to call correctly getopt function

查看:14
本文介绍了如何正确调用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: 错误:初始化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;
}

推荐答案

您在这里遗漏了两件事:

You are missing two things here:

  1. 参数列表不是字符串.它是一个字符串列表.不要被 shell 或其他要求将参数列表作为单个字符串的程序所迷惑.在一天结束时,这些程序会将字符串拆分为参数数组并运行一个可执行文件(参见 execv,例如).
  2. 参数列表中总是有一个隐式的第一个参数,它是程序名称.

这是您的代码,已修复:

Here is your code, fixed:

#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆