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

你离开我真会死。 提交于 2019-12-13 08:30:06

问题


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


来源:https://stackoverflow.com/questions/14482852/how-to-read-only-digits-from-input-no-letters-just-digits-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!