-2

I am trying to convert an array that contains string into a float. Every string at index [j][2] will be a number which must be converted into a float. i is an int that contains the total number of "rows" of the array. First, I need to multiply it by 8 and then divide by 10, then convert it into a string and store it back into the array. I want to convert it into a float again at a later time but I need a record of which index each float belongs to. So I need a reliable method of converting string into floats. The following fails and gives me this error message:

for (int j = 0; j < i; j++) {
    float wow = strtof(array[j][2]);
    array[j][3] = (wow + float(i/10)*8);
}

Error:

cannot convert ‘std::string {aka std::basic_string}’ to ‘const char*’ for argument ‘1’ to ‘float strtof(const char*, char**)’

Variations of strtof like stof and atof give me the same error.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Reginsmal
  • 127
  • 9
  • The simple answer here is to use `array[j][2].c_str()`, and there are many variations of questions asking about similar function calls. – crashmstr Nov 19 '15 at 17:15
  • Given the error message, also a "true" duplicate of [How to convert a std::string to const char* or char*?](http://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char) – crashmstr Nov 19 '15 at 17:16

1 Answers1

4

You are using the wrong function. To convert a std::string to a float you need to use std::stof not strtof.

Note: std::stof requires C++11 or higher. If you do not have that you can use atof but you need to use c_str().

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • I do not have C++11. However, when I use `float wow = strtof(array[j][2].c_str())`, It says there are too few arguments. – Reginsmal Nov 19 '15 at 17:19
  • @Reginsmal I had a mistake in my answer. You should use `atof` if you do not have C++11. `float wow = atof(array[j][2].c_str())` – NathanOliver Nov 19 '15 at 17:26