本文介绍了将argv转换为某种东西并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个带有参数的函数

foo(int argc, char* argv[]是我不想编辑/修补的可移植库.

我如何将main的argv存储在以后的地方.因此,我可以执行以下操作.

Hi,

I have a function which takes the arguments

foo(int argc, char* argv[] which is a portable library which I do not want to edit/patch.

How do I store the argv from main somewhere for later use. So i could do the following.

 myStoredArguments = storeArguments(argc,argv); // Store

    foo(myStoredArguments.getArgc(),myStoredArguments.getArgv()); // Restore
}



必须维护args的顺序.我看过了

std::string myString* = new std::string[argc],但这似乎并没有创建字符串数组,而是创建了一个带有数组的字符串.希望这很有意义,累了.

请注意,Microsoft也将在gcc上启用此功能.

谢谢,
Iain



The order of the args must be maintained. I did look at

std::string myString* = new std::string[argc] but this did not seem to create an array of strings but rather a string with an array. Hope this makes sense, tired.

Note this will be on gcc as well are microsoft.

Thanks,
Iain

推荐答案


std::vector<std::string> _arguments;

int main(int argc, char * argv[])
{
    _arguments = std::vector<std::string>(argv, argv + argc);
    // ...



在Emilio的评论之后添加:

实际上,它开始将您的代码从C迁移到C ++,下一步将重写您的foo()函数以接受std::vector<std::string>&

在这两者之间,正如Emilio的评论所指出的那样,您将需要一个适配器来使用现有的foo(),例如,使用(VC2010或gcc 4.5)C ++ 0x lambdas:



Added after Emilio''s comment:

Indeed it starts to migrate your code from C to C++, next step will rewrite your foo() function to accept a std::vector<std::string>&

In between, as Emilio''s comment points, you would need an adaptor to use your existing foo(), for instance using (VC2010 or gcc 4.5) C++0x lambdas:

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

std::vector<std::string> _arguments;

void foo(int argc, char* argv[])
{
    std::copy_n(argv, argc, std::ostream_iterator<char*>(std::cout, " "));
    std::cout << std::endl;
}

void CallFoo(std::vector<std::string>& args)
{
    std::vector<const char *> argv(args.size());
    std::transform(args.begin(), args.end(), argv.begin(), [](std::string& str){
        return str.c_str();});
    foo(argv.size(), const_cast<char**>(argv.data()));
}

int main(int argc, char * argv[])
{
    _arguments = std::vector<std::string>(argv, argv + argc);
    CallFoo(_arguments);
    return 0;
}




欢呼声,
AR




cheers,
AR


class Args
{
  int _argc;
  char ** _argv;
public:
  Args(int argc, char * argv[])
  {
    _argc = argc;
    if (_argc > 0)
    {
      _argv = new char *[argc];
    }
    for (int n = 0; n < argc; n++)
    {
      _argv[n] = new char[strlen(argv[n])+1];
      strcpy(_argv[n], argv[n]);
    }
  }
  ~Args()
  {
    if (_argc > 0)
    {
      for (int n = 0; n < _argc; n++)
        delete [] _argv[n];
      delete [] _argv;
    }
  }
  int get_argc(){ return _argc;}
  char ** get_argv(){ return _argv;}
};




这篇关于将argv转换为某种东西并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 00:13