Question

I've got a large collection of CSV lines that I'm breaking up line-by-line, splitting up by the commas, and placing those tokens in a vector.

Here's the little code snippet where I handle the last two items in that sentence:

//token for parser
        string token;

        //turn into a string stream
        istringstream ss(line);

        //ye olde vector to put things in
        std::vector<float> lineContainer;
        while(getline(ss, token, ','))
        {
            lineContainer.push_back(::atof(token));
        }

When I attempt to compile, I get the following:

Error: cannot convert 'std::string' to "const char*' for argument '1' to 'double atof(const char*)'.

In other words, converting strings to floats is a no-no, at least how I'm doing it.

How do I convert this data type to a float? I thought it would be straight-forward, but I'm very inexperienced in C++ (much better in C#, I promise) and have yet to catch all of the nuances of doing things I take for granted in other languages.

Was it helpful?

Solution

token is of type std::string. atof takes a c-string or const char* pointer to a nul-terminated array of characters.

lineContainer.push_back(::atof(token.c_str()));

http://www.cplusplus.com/reference/string/string/c_str/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top