PDA

View Full Version : cstrings and c++ strings and float




mmmdreg
Apr 21, 2005, 05:59 AM
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!



HiRez
Apr 21, 2005, 06:30 AM
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.

HiRez
Apr 21, 2005, 06:38 AM
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.

Mitthrawnuruodo
Apr 21, 2005, 06:52 AM
I believe the return value is non-zero for successThat is correct, though EOF is returned if en error occors before first field is assigned...

mmmdreg
Apr 21, 2005, 06:55 AM
HiRez: thanks! you're a champ! it worked perfectly =)