C 模板函数以将字符串分为数组

C++ template function to split string to array

本文关键字:字符串 数组 函数      更新时间:2023-10-16

我读了一个文本文件,其中包含每条线包含由空格或逗号等定界符分隔的数据,我的函数将字符串拆分为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);