chipKIT® Development Platform

Inspired by Arduino™

sscanf() double

Created Sat, 11 Jan 2014 18:28:25 +0000 by pito


pito

Sat, 11 Jan 2014 18:28:25 +0000

Sorry for messing with double, but I need another advice: I want to read a double from string:

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

void setup() 
{
  Serial.begin(115200);
  while(!Serial);  // Wait for the PC to open the port
  delay(3000);
}

void loop()  {	
	char prtbuf[25];
	double fff;
	
	char buf[] = "0.76484218728448842625";

	sscanf( buf, "%e", &fff);   // ????
	
	//fff = 0.76484218728448842625;
	
	// print double - the workaround
	sprintf(prtbuf, "%1.15e", fff);
	Serial.print(prtbuf);
	
	while(1);
}

I would expect

7.648421872844884e-01

as when uncommenting the fff var.

But I get

5.244051909780111e-315

majenko

Sat, 11 Jan 2014 19:17:27 +0000

One of the many advantages of using Linux over WIndows is you have man pages at your finger tips. One useful one is the "man sscanf" one, which tells me, amongst other things:

f Matches an optionally signed floating-point number; the next pointer must be a pointer to float. e Equivalent to f. g Equivalent to f. E Equivalent to f.

And:

l Indicates either that the conversion will be one of d, i, o, u, x, X, or n and the next pointer is a pointer to a long int or unsigned long int (rather than int), or that the conversion will be one of e, f, or g and the next pointer is a pointer to double (rather than float). Specifying two l characters is equivalent to L. If used with %c or %s the corresponding parameter is considered as a pointer to a wide character or wide-character string respectively.

Which means you need to use %lf not %e.


pito

Sun, 12 Jan 2014 09:43:54 +0000

Thanks! :)