c - 如何在 C 中仅读取输入中的数字(没有字母,只有数字)?

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

最佳答案

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

关于c - 如何在 C 中仅读取输入中的数字(没有字母,只有数字)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482852/

相关文章:

c++ - 用C++输入十六进制和读取十六进制

html - 停止导致回发的文本框

c# - 使用 Awesomium 捕获网络错误

c - realloc导致的malloc错误

c - 大 O 符号运行时

c - Eclipse C Build 选定的文件不生成可执行文件

c - 为目标文件中的指令分配地址

python - while循环在Python中连续运行,输入好还是不好?

python - OSError : [Errno 22] Invalid argument on file path while modifying a file

vb.net - 错误: 'AddRange' is not a member of 'System.Array'