-1

Iam new to C and I have a problem with adding and printing some doubles in 09.3f format. This is my code:

#include <stdio.h>

int main(int argc, char **argv)
{
   double d, m, c;


   scanf("%1f", &d);

   scanf("%1f", &m);

   c = d + m;
   printf("%09.3f\n", c);


}

And I have typed twice scanfyet I can only insert 1 number, why is that? what i get from the printf is 00000.000

Example: d = 5,125 and m = 1.256, then i want C to be: 00006.381

Siguza
  • 21,155
  • 6
  • 52
  • 89

3 Answers3

1

Code is using a width limit of 1 in scanf("%1f", &d);. That digit one limits the user input to 1 non-whitespace character and then attempts to save the result in a float. Results are not defined.

Be sure to enable all warnings. Many compilers will warn that double d; scanf("%1f", &d); do not match.

To save input to a double use an ell l. @Alter Mann Be sure to check results too.

//          ell, not one
//          v 
if (scanf("%lf", &d) != 1) puts("Number was not entered.");
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

Don't use scanf ever; it is broken-as-specified.

Use getline to read an entire line (if you don't have getline, fgets will do), and then strtod to parse it into numbers. (In this case it's possible to do the entire job with just strtod, but you may find it easier to write code that splits up the line with strsep first. If you don't have strsep, strtok will do.)

Once you make those changes your program should work.

zwol
  • 135,547
  • 38
  • 252
  • 361
  • Thanks for the tip, but i also want to try it with scanf, The problem is I typed 2 scanf but it reads only one double. Why is that? – Youssef Sakuragi Sep 07 '16 at 12:51
  • Probably the peculiar and inconvenient way `scanf` treats the space character *between* the numbers and/or the carriage return *after* one or both of the numbers, but I don't actually bother remembering how `scanf` works in detail, because it's so broken that the only thing worth knowing about it is that it shouldn't be used. – zwol Sep 07 '16 at 12:53
  • Thanks for your time and tips! getline also worked, and I figured it out with the scanf – Youssef Sakuragi Sep 07 '16 at 13:01
-2

Here, might be Input Buffer Problems With Scanf. So, you can add a space in the scanf. like,

 scanf("%lf", &d);

 scanf(" %lf", &m);

Also, use %lf in scanf instead of %1f.

msc
  • 33,420
  • 29
  • 119
  • 214