Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sscanf for doubles

Tags:

c

scanf

This is a simple problem, but I can't see it:

  char *s = "f 8.649292" ;
  double d ;
  sscanf( s, "f %f", &d ) ;

  printf( "d is %f\n", d ) ;

Why is d not containing the double value 8.649292?

like image 454
bobobobo Avatar asked Apr 25 '10 01:04

bobobobo


People also ask

How do I scanf double?

To read a double, supply scanf with a format string containing the conversion specification %lf (that's a lower case L, not a one), and include a double variable preceded by an ampersand as the second parameter.

What is sscanf used for in C++?

The sscanf() function in C++ is used to read the data from string buffer.

What value does sscanf return?

The sscanf() function returns the number of fields that were successfully converted and assigned. The return value does not include fields that were read but not assigned. The return value is EOF when the end of the string is encountered before anything is converted.


1 Answers

Oh wait, nevermind. d needs to be a float.

And to make it work you could use %lf for a double

  char *s = "f 8.649292 " ;
  double d ;
  sscanf( s, "f %lf", &d ) ;

  printf( "d is %lf\n", d ) ;
like image 50
bobobobo Avatar answered Nov 06 '22 00:11

bobobobo