开发者

How do I benefit from argc and argv in C++, the standard way? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying th开发者_Python百科is question so that it can be reopened, visit the help center. Closed 12 years ago.

What is the standard way to retrive and check for the argc and argv and what is the best usage and how to do that in linux?

Please provide examples.

"I want to have a complex command-line options and I want to use them in my application" That what I mean.

Thanks


There are (at least) two ways to write your main function:

int main()
{
}

and

int main(int argc, char* argv[])
{
}

If you use the second option, then your command line arguments will be in argv, which has argc # of elements:

#include <iostream>
int main(int argc, char* argv[])
{
  for (int i = 0; i < argc; ++i)
  {
    std::cout << "arg #" << i << ": " << argv[i] << std::endl;
  }
}


Please use boost program options http://www.boost.org/doc/html/program_options.html for access to the command arguments.


What do you want to do with them?

A simple example of usage is like the following:

// Get numbers from the command line, and put them in a vector.
int main(int argc, char* argv[])
{
    /* get the numbers from the command line. For example:

           $ my_prog 1 2 3 4 5 6 7 8 9 10
    */
    std::vector<int> numbers(argc-1);
    try
    {
        std::transform(argv+1, argv+argc, numbers.begin(),
                       boost::lexical_cast<int, char*>);
    }
    catch(const std::exception&)
    {
        std::cout << "Error: You have entered invalid numbers.";
    }
}

It depends on what you are trying to do. If you have many types of arguments etc.. Then it is better to use something like boost program options.


int main(int argc, char* argv[])
{
    for(int i = 0; i < argc; i++)
        printf("%s\n", argv[i]);
}

Works in both C and C++, though in C++ you should include cstdio and in C you should include stdio.h.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜