scanf("%d ",&i) 的问题

2022-01-15 00:00:00 format c c++ scanf formatted-input

对于此代码:

int i;
scanf("%d
",&i);

在我输入两个数字之前,我无法停止我的程序.

I am not able to stop my program until I input two numbers.

我觉得很奇怪,我知道什么时候输入合适,scanf会返回1.当我输入12a 'Enter'"、12 'Enter'2"等时,没关系,i = 12,似乎当我输入不同的int或输入'Enter'和另一个时,scanf 返回 1.

I think it is very strange ,I know when the input is suitable,the scanf will return 1. When I input "12a 'Enter'","12 'Enter'2" and so on ,it is ok,the i=12,it seems that when I input something is different int or input a 'Enter' and something another,the scanf returns 1.

我错过了什么?

推荐答案

"当我使用 scanf("%d ",& 时,我必须输入两个数字才能停止我的程序;i);"
虽然这种格式使 scanf 读取数字并将其存储到 i 中,但这种读取"会继续并持续到非空白字符后跟 .这就是输入 1 2 使 scanf 停止的原因.

"I am not able to stop my program until I input two numbers when I use scanf("%d ",&i);"
Although this format makes scanf read the number and store it into i, this "reading" continues and it lasts till non-whitespace character followed by is found. This is the reason why input 1 2 makes this scanf stop.

在这种情况下,您不应在输入格式中指定换行符.请改用 scanf("%d",&i);.

You should not specify newline in the input format in this case. Use scanf("%d",&i); instead.

相关文章