Home C++ template function to split string to array
Reply: 2

C++ template function to split string to array

Mohamed Mousa El-Kheshen
1#
Mohamed Mousa El-Kheshen Published in 2017-12-07 14:17:57Z

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'

so how could I make the casting in the template function?

jdehesa
2#
jdehesa Reply to 2017-12-07 14:31:31Z

You cannot do:

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

In your case, you could declare a template, e.g. from_string<T>, and replace the line with:

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...
Paolo Panvini
3#
Paolo Panvini Reply to 2017-12-07 14:31:39Z

You could use the strtof function (http://en.cppreference.com/w/cpp/string/byte/strtof)

so something like this

GLfloat f = std::strtof (item.c_str(), nullptr);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300545 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO