繁体   English   中英

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

[英]C++ template function to split string to array

我读了一个包含行的文本文件,每行包含用定界符分隔的数据,例如空格或逗号,我有一个将字符串拆分为数组的函数,但我想使其成为模板,以获取字符串旁边的不同类型(例如浮点数或整数),我做了两个函数,一个用于拆分为字符串,另一个用于浮点

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())从字符串中获取浮点数,当我将模板函数与浮点数结合使用时,我会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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM