本文介绍了C ++ /升压:编写一个更强大的sscanf更换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想C ++编写一个函数来替换C的sscanf的是分配火柴迭代器。
I want to write a function in C++ to replace C's sscanf that assigns the matches to iterator.
基本上,我想是这样的:
Basically, I want something like:
string s = "0.5 6 hello";
std::vector<boost::any> any_vector;
sscanv(s, "%f %i %s", any_vector);
cout << "float: " << any_cast<float>(any_vector[0]);
cout << "integer: " << any_cast<integer(any_vector[1]);
cout << "string: " << any_cast<string>(any_vector[2]);
的具体细节可能会有所不同,但你的想法。实施任何想法?
The exact details may vary, but you get the idea. Any ideas for implementation?
选项到目前为止随着问题至今:
Options so far along with problems so far:
- 的std :: istringstream :有没有操纵匹配的恒定前pressions
- Boost.Regex :不知道这是否会工作,似乎对这个复杂得多必要
- Boost.Spirit :不认为这会为动态生成的格式字符串工作,它也似乎更复杂然后必要
- 的sscanf :这是可行的,而且是不规范等,并使用以来在编译时确定的参数个数这将需要大量的开销
- std::istringstream: there's no manipulator for matching constant expressions
- Boost.Regex: not sure if this will work and it seems much more complicated than necessary for this
- Boost.Spirit: don't think this will work for dynamically generated format strings and it also seems more complicated then necessary
- sscanf: it would work, but is non-standard, etc, and using it would require a lot of overhead since the number of arguments is determined at compile time
推荐答案
有什么看法?
void sscanf(std::string str,
const std::string& format,
std::vector<boost::any>& result)
{
std::string::const_iterator i = format.begin();
while (i != format.end())
{
if (*i == '%')
{
++i; // now *i is the conversion specifier
char specifier = *i;
++i; // now *i is the next seperator
std::string extract = str.substr(0, str.find(*i));
switch (specifier)
{
// matching an integer
case 'i':
result.push_back(boost::lexical_cast<int>(extract));
break;
// matching a floating point number
case 'a': case 'e': case 'f': case 'g':
result.push_back(boost::lexical_cast<float>(extract));
break;
// matching a single character
case 'c':
result.push_back(boost::lexical_cast<char>(extract));
break;
// matching a string
case 's':
result.push_back(extract);
break;
// Invalid conversion specifier, throwing an exception
default:
throw std::runtime_error("invalid conversion specifier");
break;
}
}
else
{
// if it's not a %, eat!
str.erase(0, str.find(*i)+1);
++i;
}
}
}
有些转化符缺少 - 但主要是它的工作原理。
Some conversions specifiers are missing – but principally it works.
这篇关于C ++ /升压:编写一个更强大的sscanf更换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!