C:scanf函数对于char未正常工作 [英] C: scanf for char not working as expected
问题描述
我最近跑在我的电脑的C程序。它有一个for循环中,一些焦炭d被扫描。 for循环运行3次。在每个运行它打印运行的计数,然后扫描炭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\n", f);
scanf("%c", &d);
}
return 0;
}
现在的麻烦是,当我运行程序时,为跳过scanf函数一部分,当f为1。
现在,如果我改变了code如下:
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\n", f);
scanf("%d", &d);
}
return 0;
}
现在该程序工作正常。并为循环的每个迭代执行scanf函数。
Now the program works fine. and scanf is executed for every iteration of for loop.
什么似乎是这里的问题?我的意思是,当d为类型诠释它工作正常,但是当d为类型的字符就不能正常工作。
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()的
将考虑pviously进入了$ P $ ENTER
键preSS。
Otherwise, scanf()
will consider the previously entered ENTER
key press.
请注意:
-
<大骨节病> ENTER 骨节病>键preSS生成一个
\\ n
,这是一个vaild输入% ç
格式说明。前%C
添加一个空格告诉scanf()的
忽略所有前导空格样的投入(包括previously存储\\ n
),并读标准输入
的第一个非空白字符。
ENTER key press generates a
\n
, 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\n
) and read the first non-whitespace character fromstdin
.
至于与的情况下,%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:scanf函数对于char未正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!