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

2019-09-21 15:46发布

问题:

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

回答1:

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


回答2:

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