Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

c++ - Is there a way to use QCommandLineParser with an option followed by multiple values?

I need to make my app scan for a number of ports given as command line arguments and so far I have this:

    QCommandLineOption portScanOption(QStringList() << "p" << "target-port",
                QCoreApplication::translate("main", "Scan <port> for other instances"),
                QCoreApplication::translate("main", "port"));
    parser.addOption(portScanOption);
    parser.process(app);
    auto ports = parser.values(portScanOption); // do something with the ports

In order for this to work correctly, I need to pass the arguments like this: -p 5000 -p 7000 -p 8000. I am looking for a way to make this work for the following input: -p 5000 7000 8000, but I haven't been able to find anything, not even in the official documentation. It's something quite trivial, so I expect Qt to have something like this. Do you guys know how it should be done?

question from:https://stackoverflow.com/questions/65945504/is-there-a-way-to-use-qcommandlineparser-with-an-option-followed-by-multiple-val

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is already handled - the syntax you propose doesn't quite fit QCommandLineParser. Either use -p 5000,7000,8000 or -p "5000 7000 8000". All those ports will be the value of the port option, and you can then separate them with split(QRegularExpression("[, ]"), Qt::SkipEmptyParts) (that's QString::split). E.g.:

auto ports = parser.value("target-port")
             .split(QRegularExpression("[, ]"), Qt::SkipEmptyParts);
for (auto &portStr : ports) {
  bool ok = false;
  int port = portStr.toInt(&ok);
  if (!ok) continue;
  // use port value here
}

Alternatively, since the Qt source code is available, you could copy the command line parser source into your project, rename the class, and extend it to support the original syntax you had in mind.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...