如何只读取C中输入的数字(无字母,只是数字)?

时间:2013-01-23 15:10:29

标签: c input error-handling user-input

你刚才读了一行就帮我了。现在,我想只读取输入的数字 - 没有字母,只有5位数。我怎么能这样做?

我的解决方案无法正常运行:

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

2 个答案:

答案 0 :(得分:2)

使用break语句,永远不会执行go = true;。因此,循环while (!go)是无限的。

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

答案 1 :(得分:0)

试试这个:

#include<stdio.h>
int main()
{
char  c;
        while( ( c = getchar()) != EOF  &&  c != '\n' &&  c >= 48  && c <= 57 )
        {
          printf("%c\n",c);
        }
return 0;
}
相关问题