简体   繁体   中英

Command-line arguments in C++

Many of my programs take in command-line arguments, one example is as follows:

a.out [file-name] [col#] [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.      
} 

如果你想省去自己解析cmd行参数的艰苦工作,你总是可以使用诸如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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM