scanf + printf with doubles

I recently had a problem that I was using printf with %E and doubles, but when I did a scanf to read the values back it they always failed.

I couldn’t figure out the problem, till I realised that %E, scientific notation, isnt supposed to be used for doubles.

Its very surprising that printf works one way, but the scanf doesnt work on the way back.

dragon hunters download

I wrote this little test program. It clearly shows that you should always is &lf when reading and writing doubles.

#include <stdio.h>
int main(int argc, char** argv) {
  const char * str = "-1.234E003";
  double d = 0;
  // check scanf
  printf("  scanf\n");
  sscanf(str, "%E", &#038;d);
  printf("%%E = %lfE\n", d);
  d = 0;
  sscanf(str, "%G", &#038;d);
  printf("%%G = %lf\n", d);
  d = 0;
  sscanf(str, "%f", &#038;d);
  printf("%%f = %lf\n", d);
  d = 0;
  sscanf(str, "%lf", &#038;d);
  printf("%%lf = %lf\n", d);
  // now check printf
  printf("  printf\n");
  printf("%%E = %E\n", d);
  printf("%%G = %G\n", d);
  printf("%%f = %f\n", d);
  printf("%%lf = %lf\n", d);
  return 0;

download the ice storm online

When you compile this and run it you get this

%E = 0.000000E
%G = 0.000000
%f = 0.000000
%lf = -1234.000000
%E = -1.234000E+003
%G = -1234
%f = -1234.000000
%lf = -1234.000000

Clear the printf works fine but the scanf cant cope with the doubles.

I’m not sure whether its documented what should happen when you use the incorrect printf or scanf variables (e.g %d) with the incorrect argument type (i.e float not a integer).

download alive lost stallions the journey home movie

Leave a Reply