converting strings to floats with "strtof" isn't working for me

I'm trying to convert a string to a float and I can't figure it out as my code keeps failing to compile at the line where I use the strtof function, can anyone help? I've read http://www.cplusplus.com/reference/cstdlib/strtof/ and as far as I can tell I'm doing it right.

I currently have this as my code:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>

using namespace std;

int main ()
{
string str_name="23423.34"
float a;

a = strtof (str_name, NULL);

cout << a;

return 0;
}
It's either stof(str_name) (demo: http://coliru.stacked-crooked.com/a/2d045078cf8e3248 )
or strtof(str_name.c_str(), NULL) (demo: http://coliru.stacked-crooked.com/a/ce21607912185212 )
Four issues:

1. Put code in [code][/code] tags
2. Post the errors you get
3. You are missing a semicolon on the line declaring your string
4. strtof takes a c-string, not an std::string, so change to a = strtof (str_name.c_tr(), NULL);

Is there any reason you cannot use std::stof?

http://www.cplusplus.com/reference/string/stof/
i didn't know of std::stof and the semicolon is just a mistake i made when typing it into the forum but thanks for the info on posting.

but with your example does anything need to be in the parenthesis?

Last edited on
nevermind Cubbi's demo answered my question thanks for the help.
but with your example does anything need to be in the parenthesis?

I assume that you refer to this: [..].c_tr()[..]? If so, no, nothing needs to be in those parenthesis:

http://www.cplusplus.com/reference/string/string/c_str/
Topic archived. No new replies allowed.