如何在C++中实现以下代码(Python伪代码)?
if argv[1].startswith('--foo='):
foo_value = int(argv[1][len('--foo='):])
(例如,如果argv[1]
为--foo=98
,则foo_value
为98
。)
我对Boost犹豫不决,因为我只是在考虑对一个简单的小命令行工具进行非常小的更改(我宁愿不必学习如何链接和使用Boost来进行小更改)。
发布于 2016-11-06 01:36:09
使用带有搜索位置pos
参数的rfind
重载,并为其传递零:
std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) { // pos=0 limits the search to the prefix
// s starts with prefix
}
还需要别的什么吗?纯STL!
许多人将其误读为“在整个字符串中反向搜索前缀”。这将给出错误的结果(例如,string("tititito").rfind("titi")
返回2,因此与== 0
相比将返回false),而且效率将很低(查看整个字符串,而不仅仅是开始部分)。但它没有这样做,因为它将pos
参数作为0
传递,这将搜索限制为仅在该位置或更早的位置匹配。例如:
std::string test = "0123123";
size_t match1 = test.rfind("123"); // returns 4 (rightmost match)
size_t match2 = test.rfind("123", 2); // returns 1 (skipped over later match)
size_t match3 = test.rfind("123", 0); // returns std::string::npos (i.e. not found)
发布于 2009-12-10 09:07:31
你可以这样做:
std::string prefix("--foo=");
if (!arg.compare(0, prefix.size(), prefix))
foo_value = std::stoi(arg.substr(prefix.size()));
寻找像Boost.ProgramOptions这样的库来为您做这件事也是一个好主意。
发布于 2009-12-10 09:03:42
如果你已经在使用Boost,你可以使用boost string algorithms + boost lexical cast:来完成
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>
try {
if (boost::starts_with(argv[1], "--foo="))
foo_value = boost::lexical_cast<int>(argv[1]+6);
} catch (boost::bad_lexical_cast) {
// bad parameter
}
这种方法,就像这里提供的许多其他答案一样,对于非常简单的任务是可以的,但从长远来看,使用命令行解析库通常会更好。Boost有一个(Boost.Program_options),如果你碰巧已经在使用Boost,这可能是有意义的。
否则,搜索"c++命令行解析器“将会出现许多选项。
https://stackoverflow.com/questions/1878001
复制相似问题