cstrings and c++ strings and float

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

  1. macrumors 65816

    mmmdreg

    Joined:
    Apr 14, 2002
    Location:
    Sydney, Australia
    #1
    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

    HiRez

    Joined:
    Jan 6, 2004
    Location:
    Western US
    #2
    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

    HiRez

    Joined:
    Jan 6, 2004
    Location:
    Western US
    #3
    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 emeritus

    Mitthrawnuruodo

    Joined:
    Mar 10, 2004
    Location:
    Bergen, Norway
    #4
    That is correct, though EOF is returned if en error occors before first field is assigned...
     
  5. thread starter macrumors 65816

    mmmdreg

    Joined:
    Apr 14, 2002
    Location:
    Sydney, Australia
    #5
    HiRez: thanks! you're a champ! it worked perfectly =)
     

Share This Page