tags:

views:

236

answers:

4

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

+3  A: 
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.

jer
-1 for recommending printf
Noah Roberts
As opposed to correctly answering the actual question? I'm no C++ expert, so excuse my ignorance, but what's so horrendous about `printf`?
Jeriko
If the question had been tagged as C then printf would be OK. But this question is tagged C++ so you should be using the type safe mechanism provided to you be the language not relying on backward compatibility with another language.
Martin York
+4  A: 

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[argc] << std::endl;
  }
}
Bill
+1 for using C++ streams.
Noah Roberts
+4  A: 

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

Pavel Radzivilovsky
+1 for showing OP where to buy a wheel rather than build one.
Noah Roberts
+3  A: 

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.

AraK
+1 for std::transform
Noah Roberts