将std::string转换为任意数字类型或std::string的成员函数模板
Member Function Template to Covert a std::string to Any Numeric Type or to a std::string
请考虑成员函数模板。我的问题嵌入在评论表单中。
template<typename T>
GetValueResult GetValue(
const std::string &key,
T &val,
std::ios_base &(*manipulator)(std::ios_base &) = std::dec
)
{
// This member function template is intended to work for all built-in
// numeric types and std::string. However, when T = std::string, I get only
// the first word of the map element's value. How can I fix this?
// m_configMap is map<string, string>
ConfigMapIter iter = m_configMap.find(key);
if (iter == m_configMap.end())
return CONFIG_MAP_KEY_NOT_FOUND;
std::stringstream ss;
ss << iter->second;
// Convert std::string to type T. T could be std::string.
// No real converting is going on this case, but as stated above
// I get only the first word. How can I fix this?
if (ss >> manipulator >> val)
return CONFIG_MAP_SUCCESS;
else
return CONFIG_MAP_VALUE_INVALID;
}
流上的<<
和>>
操作符被设计为使用以空格分隔的令牌。所以如果一个字符串看起来像"1 2",那么你的stringstream
只会在第一个<<
上读取1
。
如果你想要多个值,我建议你在流上使用循环。像这样的东西可能会…
//stringstream has a const string& constructor
std::stringstream ss(iter->second);
while (ss >> manipulator >> value) { /* do checks here /* }
我建议你看看Boost,特别是lexical_cast,它可能会做你想要的开箱操作
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然