Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mmmdreg

macrumors 65816
Original poster
Apr 14, 2002
1,393
0
Sydney, Australia
I want to change a string to a float. What is contained in the string *is* a float (eg. string foo = "38.5"). I don't think there is a way of converting it straight off so I figure I have to change it into a character array and then apply strtof on it.

Problem is, I'm a n00b and don't really know how to use cstrings properly. So could someone please paste a few lines of code to change my string into a float? Thanks!
 
mmmdreg said:
I want to change a string to a float. What is contained in the string *is* a float (eg. string foo = "38.5"). I don't think there is a way of converting it straight off so I figure I have to change it into a character array and then apply strtof on it.
You could use sscanf:

char *foo="38.5";
float result = 0.0;
int error = sscanf(foo, "%f", &result);
printf("Float val = %f", result);

sscanf scans a string for formatted values. First arg is your string , second is the formats you're looking to parse, then each value to stick the results into. Might be other higher-level ways to do it if you're using frameworks, most have a bunch of string-parsing functions or classes.
 
I think I messed up a tiny bit there, I believe the return value is non-zero for success, not error, so I probably shouldn't have called it "error". You'll have to look up the actual result codes for sscanf.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.