简体   繁体   中英

How to read only digits from input (no letters, just digits) in C?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM