为什么这个c程序打印两次 [英] why does this c program print twice

查看:54
本文介绍了为什么这个c程序打印两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在接受第一组输入后,这段代码每次打印两次输入一个字符"——这是为什么?

After taking in the first set of input, this code prints out "Input a character" twice each time - why is this?

推荐答案

因为你按下一个数字 PLUS enter 并且 enter 将在下次调用时被 scanf() 读取

cause you press a number PLUS enter and enter will be read by scanf() at the next call

#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程序打印两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆