简体   繁体   English

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

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

I read a text file which contains lines each line contains data separated by delimiters like spaces or commas , I have a function which split a string to array but I want to make it a template to get different types like floats or integers beside string, I made two functions one for split to strings and the the other to 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);
    }
}

the template function works fine with strings, in the other function I use atof(item.c_str()) to get the float value from string, when I use the template function with floats I get invalid cast from type 'const char*' to type 'float' 模板函数可以很好地处理字符串,在另一个函数中,我可以使用atof(item.c_str())从字符串中获取浮点数,当我将模板函数与浮点数结合使用时,我会invalid cast from type 'const char*' to type 'float'

so how could I make the casting in the template function? 那么如何在模板函数中进行转换呢?

You cannot do: 您不能:

T f = static_cast<T>(item.c_str());

In your case, you could declare a template, eg from_string<T> , and replace the line with: 在您的情况下,您可以声明一个模板,例如from_string<T> ,并将该行替换为:

T f = from_string<T>(item);

The you would implement it with something like: 您将通过以下方式实现它:

// 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...

You could use the strtof function ( http://en.cppreference.com/w/cpp/string/byte/strtof ) 您可以使用strtof函数( http://en.cppreference.com/w/cpp/string/byte/strtof

so something like this 所以像这样

GLfloat f = std::strtof (item.c_str(), nullptr);

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

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