Shop OBEX P1 Docs P2 Docs Learn Events
sscanf() challange — Parallax Forums

sscanf() challange

I'd like to convert strings to floats. The internet says the standard way to do this is the atof() function but I haven't found that in the stdlib of FlexC so I use sscanf().

bool ReadFlt (float* f)
{
  char buf[16];
  *f= 1.0;
  if (!ReadStr (buf, 16, LF)) return false;
  printf ("buf = %s\n", buf);
  return sscanf (buf, "%f", f);
}

Unfortunatelly, I get this

buf = 0.760
result = 0.000000
buf = 1.800
result = 0.000000

The result is 0.0 and not 1.0, so sscanf does at least overwrite my f variable but not with the value I expect. Can anybody see what I do wrong?

Comments

  • It looks like scanf has bit-rotted somehow. I'll look into it. In the meantime you could use atof() from stdlib.h.

  • Grrr, I don't know if I'm just getting old or I have some autistic genes. I'm much better at writing my own code than finding out clues about what others have written. The atof() function is there. I just have to #include <stdlib.h>.

    bool ReadFlt (float* f)
    {
      char buf[16];
      if (!ReadStr (buf, 16, LF)) return false;
      *f= atof (buf);
      return true;
    }
    

    And now it works. Still curious why the sscanf() version didn't.

  • @ManAtWork said:
    And now it works. Still curious why the sscanf() version didn't.

    The sscanf() version didn't work because floating point support is conditionally compiled into the scanf() functions (to reduce program size for programs that don't use floating point) and the way the compiler did that changed; so did some internal functions scanf() relied on. I've checked in a fix to github for this.

Sign In or Register to comment.