How to read only digits from input (no letters, ju

2019-09-21 15:15发布

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

2条回答
\"骚年 ilove
2楼-- · 2019-09-21 15:50

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);
查看更多
劳资没心,怎么记你
3楼-- · 2019-09-21 15:58

Try with this:

#include<stdio.h>
int main()
{
char  c;
        while( ( c = getchar()) != EOF  &&  c != '\n' &&  c >= 48  && c <= 57 )
        {
          printf("%c\n",c);
        }
return 0;
}
查看更多
登录 后发表回答