How do I benefit from argc and argv in C++, the standard way? [closed]
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.
精彩评论