[英]scanf() in while loop. Put a space before % doesn't work
double bet = 0;
do
{
printf("How much would you like to bet? The minimum bet is $5.00: ");
scanf(" %.2lf",&bet);
} while (bet < 5);
My scanf just takes value once and goes into infinite loop. 我的scanf只取值一次,并进入无限循环。 I have read many posts, and found the general way to solve this is put a space before %.
我读了很多文章,发现解决此问题的一般方法是在%之前加一个空格。 I did this, but the problem still exists.
我这样做了,但是问题仍然存在。 Say it first read bet = 4, and it is supposed to ask me to enter a number again, but it just keeps printing "How much would you like to bet? The minimum bet is $5.00: ".
假设它首先读取bet = 4,并且应该让我再输入一个数字,但它只会继续打印“您想下多少赌注?最低下注为$ 5.00:”。 Why is that?
这是为什么?
The problem is your scanf
format string. 问题是您的
scanf
格式字符串。 Your compiler might have warned about it. 您的编译器可能已对此发出警告。 The
.
的
.
isn't allowed. 不允许。 As a result, the
scanf
call is returning 0
and is not consuming any characters. 结果,
scanf
调用返回0
,并且不占用任何字符。
Try changing it to this: 尝试将其更改为此:
double bet = 0;
do {
printf("How much would you like to bet? The minimum bet is $5.00: ");
scanf(" %lf", &bet);
} while (bet < 5);
It would also be a good idea to check the return value from scanf
. 检查
scanf
的返回值也是一个好主意。 It should return the number of values successfully decoded. 它应该返回成功解码的值的数量。
Is .2 is required in your code. 您的代码中是否需要.2。 It is showing warning as a use of .
使用表示警告。 in the code.
在代码中。 Try removing it.
尝试将其删除。 Then it is working fine.
然后工作正常。 ie use only %lf
即仅使用%lf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.