如何在C只读从输入数字(没有字母,数字只是)? [英] How to read only digits from input (no letters, just digits) in C?

查看:212
本文介绍了如何在C只读从输入数字(没有字母,数字只是)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您在读取行帮我前一阵子。现在,我想读取仅输入数字 - 没有字母,只有5位数字。我怎样才能做到这一点?

我的解决方案不能正常工作:

  INT I = 0;
而(!去)
    {
        的printf(给5位:\\ n \\ n);
        而((C =的getchar())= EOF和放大器;!&安培;!C ='\\ n'和;&安培;我小于5)
        {
            INT位= C - '0';
            如果(数字> = 0&放大器;&功放;数字< = 9)
            {
                输入[我++] =数字;
                如果(我== 5)
                {
                    打破;
                    去= TRUE;
                }
            }
        }
    }


解决方案

随着语句,去= TRUE; 将永远不会被执行。因此,循环而(走!)是无限的。

 的#include<&文件ctype.h GT;
#包括LT&;&stdio.h中GT;INT I = 0;
INT输入[5];的printf(给五个数字:);
fflush(标准输出);做
{
  C =的getchar();  如果(ISDIGIT(c))的
  {
    输入[I] = C - '0';
    I = I + 1;
  }
}而(ⅰ小于5);

You helped me a while ago with reading a line. Now, I want to read only digits from input - no letters, just 5 digits. How can I do this?

My solution doesn't work properly:

int i = 0; 
while(!go)
    {
        printf("Give 5 digits: \n\n");
        while( ( c = getchar()) != EOF  &&  c != '\n' &&  i < 5 )
        {
            int digit = c - '0';
            if(digit >= 0 && digit <= 9)
            {
                input[i++] = digit;
                if(i == 5)
                {
                    break;
                    go = true;
                }
            }
        }
    }

解决方案

With the break statement, go = true; will never be executed. Therefore the loop while (!go) is infinite.

#include <ctype.h>
#include <stdio.h>

int i = 0;
int input[5];

printf ("Give five digits: ");
fflush (stdout);

do
{
  c = getchar ();

  if (isdigit (c))
  {
    input[i] = c - '0';
    i = i + 1;
  }
} while (i < 5);

这篇关于如何在C只读从输入数字(没有字母,数字只是)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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