问题描述
我最近在我的电脑上运行了一个 c 程序.它有一个 for 循环,其中扫描了一些 char d.for 循环运行 3 次.在每次运行期间,它会打印运行计数,然后扫描 char d 的值.程序如下
I was recently running a c program in my PC. It have a for loop in which some char d is scanned. The for loop runs for 3 times. During each running it prints the the count of running and then scans the value of char d. The program is as follows
#include<stdio.h>
int main(){
int f;
char d;
for(f=0;f<3;f++){
printf("Choice %d
", f);
scanf("%c", &d);
}
return 0;
}
现在的问题是,当我运行程序时,当 f 为 1 时,for 会跳过 scanf 部分.现在,如果我将代码更改如下
Now the trouble is that when I run the program, the for skips the scanf part when f is 1.Now if i changed the code as follows
#include<stdio.h>
int main(){
int f;
int d;
for(f=0;f<3;f++){
printf("Choice %d
", f);
scanf("%d", &d);
}
return 0;
}
现在程序运行良好.每一次for循环迭代都会执行scanf.
Now the program works fine. and scanf is executed for every iteration of for loop.
这里似乎有什么问题?我的意思是当 d 是 int 类型时它可以正常工作,但是当 d 是 char 类型时它不能正常工作.
What does seem to be the problem here? I mean when d is of type int it works fine, but when d is of type char it does not work correctly.
推荐答案
你必须改变
scanf("%c", &d);
到
scanf(" %c", &d);
^
|
否则,scanf()
会考虑之前输入的ENTER
键按下.
Otherwise, scanf()
will consider the previously entered ENTER
key press.
注意:
键按下生成一个
,这是
%c
格式说明符的有效输入.在%c
之前添加一个空格告诉scanf()
忽略所有前导的类似空格的输入(包括之前存储的)并读取
stdin
中的第一个非空白字符.
key press generates a
, which is a vaild input for
%c
format specifier. Adding a space before%c
tellsscanf()
to ignore all leading whitespace-like inputs (including that previously stored) and read the first non-whitespace character from
stdin
.
对于 %d
格式说明符的情况,它会在扫描数字输入之前消耗(并忽略)任何前导的类似空格的输入,因此第二种情况不会遇到任何问题.
As for the case with %d
format specifier, it consumes (and ignores) any leading whitespace-like inputs before scanning for numeric inputs, so the second case does not suffer any issues.
这篇关于C: char 的 scanf 没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!