c - 为什么这个c程序打印两次

标签 c stdout

#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);
                }
        }
}

接受第一组输入后,这段代码每次都会打印两次“输入一个字符” - 这是为什么?

最佳答案

因为你按下一个数字加上 Enter,并且 Enter 将在下次调用时被 scanf() 读取

#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);
    }
  }
}

关于c - 为什么这个c程序打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47062702/

相关文章:

go - 如何正确捕获所有 stdout/stderr

c - 使用 scanf 进行错误检查

c - C 中程序的双重释放或损坏 (!prev) 错误

c - 启用/禁用功能 v.s. 的基本原理改变状态?

c - 错误: indirection requires pointer operand ('int' invalid)

python - 如何使用ctypes查看python中的指针值更改

c++ - 使用 std::cout 评估参数的顺序

python ,C : redirected stdout fires [Errno 9]

python - 为什么 python 在控制台和管道中打印 unicode 字符串时表现不一样?

linux - 为什么 wget 输出到 stderr 而不是 stdout?