StokeBloke.com

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.

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

#include 

int main(int argc, char** argv) {

  const char * str = "-1.234E003";
  double d = 0;

  // check scanf
  printf("  scanf\n");
  sscanf(str, "%E", &d);
  printf("%%E = %lfE\n", d);

  d = 0;
  sscanf(str, "%G", &d);
  printf("%%G = %lf\n", d);

  d = 0;
  sscanf(str, "%f", &d);
  printf("%%f = %lf\n", d);

  d = 0;
  sscanf(str, "%lf", &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 onlin
When you compile this and run it you get this
  scanf
%E = 0.000000E
%G = 0.000000
%f = 0.000000
%lf = -1234.000000
  printf
%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).

Leave a Reply