TeddyBearWithACape
TeddyBearWithACape

Reputation: 23

Am I using conversion specifiers wrong or something? scanf() isn't working in c

scanf() isnt working properly when I use the following lines of code in c:

double withdraw = 0;

scanf("%.2lf",&withdraw);

printf("\n\nWithdraw %.2lf?",&withdraw);

and this:

double withdraw = 0;

scanf("%.2lf",withdraw);

printf("\n\nWithdraw %.2lf?",withdraw);

and this:

double withdraw = 0;

scanf("%.2lf",&withdraw);

printf("\n\nWithdraw %.2lf?",withdraw);

and finally this:

double withdraw = 0;

scanf("%.2lf",withdraw);

printf("\n\nWithdraw %.2lf?",&withdraw);

input into scanf() is ALWAYS this:

1

output of withdraw is ALWAYS this:

0.00

Please help. This seems so crazy to me!

Upvotes: 2

Views: 123

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Yes, your code is wrong. You cannot use precisions (".<int>") with fscanf() family, that's invalid. This causes causes undefined behavior.

Quoting C11, chapter §7.21.6.2/p3, fscanf()

Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

— An optional assignment-suppressing character *.

— An optional decimal integer greater than zero that specifies the maximum field width (in characters).

— An optional length modifier that specifies the size of the receiving object.

— A conversion specifier character that specifies the type of conversion to be applied.

and, p13

If a conversion specification is invalid, the behavior is undefined.


That said, do not use trial and error, undefined behaviors are tricky to catch and understand. read the manual pages for proper format specifier for any argument type.

Upvotes: 4

Yunbin Liu
Yunbin Liu

Reputation: 1498

The following could work.

#include <stdio.h>
#include <math.h>

int main()
{
    double withdraw = 0;

    scanf("%lf", &withdraw);
    printf("\n\nWithdraw %.2lf?", withdraw);

    return 0;
}

Upvotes: 0

LPs
LPs

Reputation: 16213

As your compiler is telling you

warning: unknown conversion type character ‘.’ in format [-Wformat=]

So you cannot specify precision with this type of format specifier

Upvotes: 0

Related Questions