前一段时间,您帮助我阅读了台词。现在,我只想读取输入中的数字-没有字母,只有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/