cstrings and c++ strings and float

Discussion in 'Mac Programming' started by mmmdreg, Apr 21, 2005.

  1. macrumors 65816


    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!
  2. macrumors 601


    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.
  3. macrumors 601


    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.
  4. Moderator


    Staff Member

    That is correct, though EOF is returned if en error occors before first field is assigned...
  5. macrumors 65816


    HiRez: thanks! you're a champ! it worked perfectly =)

Share This Page