Command-line arguments in C++
Many of my programs take in command-line arguments, one example is as follows:
a.out [file-name] [c开发者_运维知识库ol#] [seed]
Then if I want to use the arguments, I have nice, easy-to-use functions such as:
atof(argv[..]) and atoi(argv[..])
I was wondering if such easy/simple functions exist for C++. I tried to simply do this:
cin >> col_num >> seed;
But that doesn't work... It waits for an input (not command-line) and then outputs it...
Thanks
ato*
family is crappy, and cannot signal errors properly. In C++ you want to use either boost::lexical_cast
or a full-blown command-line parser like boost::program_options
.
Solution 1:
You can use lexical_cast
in place of atoi
int x = boost::lexical_cast<int>("12345");
Use boost::lexical_cast
in try-catch block though. It throws boost::bad_lexical_cast
when the cast is invalid.
Solution 2:
If you are not using Boost and need a standard C++ solution you can use streams.
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
If you want to save yourself the hard work of parsing the cmd line arguments yourself you can always use a library such as boost::program_options
.
If you mean to use streams and >>
operator, you can use stringstream
:
double a; // or int a or whatever
stringstream(argv[1]) >> a;
You need to include <sstream>
You can still use atof
and atoi
.
#include <cstdlib>
int main(int argc, char* argv[]) {
float f = std::atof(argv[1]);
int i = std::atoi(argv[2]);
}
But you can use more generic facilities like boost::lexical_cast
.
精彩评论