为什么这个c程序打印两次 #包括 int main() { 字符c='A'; 而(c!=',') { printf(“输入字符:”); scanf(“%c”、&c); 如果(c>='0'&&c

为什么这个c程序打印两次 #包括 int main() { 字符c='A'; 而(c!=',') { printf(“输入字符:”); scanf(“%c”、&c); 如果(c>='0'&&c,c,stdout,C,Stdout,导致您按一个数字加上enter,则在下次通话时,scanf()将读取enter #include <stdio.h> int main() { char c = 'A'; while (c != ',') { printf("Input a character:"); scanf("%c", &c); if (c >= '0'

导致您按一个数字加上enter,则在下次通话时,
scanf()
将读取enter

#include <stdio.h>

int main()
{
        char c = 'A';
        while (c != ',')
        {
                printf("Input a character:");
                scanf("%c", &c);
                if (c >= '0' && c <= '9')
                {
                        printf("%d\n", (int)c);
                }
        }
}
#包括
内部主(空){
字符c='A';
而(c!=','){
printf(“输入字符:”);
如果(scanf(“%c”,&c)!=1){
返回0;//如果用户不输入任何内容,则停止
}

如果(c>=“0”&&c在%scanf(“%c”,&c)之前插入一个空格;否则,与Enter键对应的新行字符也是readIt read the character,Write the prompt,it read a newline,Write the prompt。我100%确定这是重复的,但找不到重复的内容。当您按Enter键时,输入缓冲区中会生成一个
'\n'
(例如
stdin
)。您读取1字符,将
stdin
中的
'\n'
留在
循环的下一次迭代时读取。在格式字符串中包含
空格
(在
%c
格式说明符之前)会导致
scanf
跳过所有插入的空白(
'\n'
为空白)这是C程序员使用
scanf
进行用户输入的主要陷阱之一,也是为什么建议使用
fgets
进行用户输入的原因。“打印”输入一个字符“每次两次”是因为用户键入了两个键。
%C
前面的空格应该足够=>
%C
#include <stdio.h>

int main(void) {
  char c = 'A';
  while (c != ',') {
    printf("Input a character:");
    if (scanf("%c", &c) != 1) {
      return 0; // we stop if user don't input anything
    }
    if (c >= '0' && c <= '9') {
      printf("%d\n", (int)c); // by the way did you want (int)(c - '0') ?
    } else {
      printf("enter a number ! you enter %d\n", c);
    }
  }
}