C 模板函数以将字符串分为数组
C++ template function to split string to array
我读了一个文本文件,其中包含每条线包含由空格或逗号等定界符分隔的数据,我的函数将字符串拆分为array,但我想使其成为模板在字符串旁边获得了不同类型的类型,例如浮子或整数,我制作了两个功能,将两个功能分开为字符串,另一种是floats
template<class T>
void split(const std::string &s, char delim, std::vector<T>& result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
T f = static_cast<T>(item.c_str());
result.push_back(f);
}
}
void fSplit(const std::string &s, char delim, std::vector<GLfloat>& result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
GLfloat f = atof(item.c_str());
result.push_back(f);
}
}
模板函数与字符串正常工作,在另一个功能中,我使用 atof(item.c_str())
从字符串中获取float值,当我与浮子一起使用模板函数时,我得到 invalid cast from type 'const char*' to type 'float'
那么如何在模板功能中进行铸造?
你不能做:
T f = static_cast<T>(item.c_str());
在您的情况下,您可以声明一个模板,例如from_string<T>
,并用:
T f = from_string<T>(item);
您将使用以下内容来实现它:
// Header
template<typename T>
T from_string(const std::string &str);
// Implementations
template<>
int from_string(const std::string &str)
{
return std::stoi(str);
}
template<>
double from_string(const std::string &str)
{
return std::stod(str);
}
// Add implementations for all the types that you want to support...
您可以使用strtof函数(http://en.cppreference.com/w/cpp/string/byte/strtof)
这样的东西
GLfloat f = std::strtof (item.c_str(), nullptr);
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组