在C编程中检查输入是否为数字

在C编程中检查输入是否为数字,c,arrays,digit,C,Arrays,Digit,我目前正在读这本书:其中一个例子是,我很难理解如何检查输入是否为数字。示例见第22页,在数组一章下进行解释 下面是一个例子 #include <stdio.h> /* count digits, white space, others */ main() { int c, i, nwhite, nother; int ndigit[10]; nwhite = nother = 0; for (i = 0; i < 10; ++i) {

我目前正在读这本书:其中一个例子是,我很难理解如何检查输入是否为数字。示例见第22页,在数组一章下进行解释

下面是一个例子

#include <stdio.h>

 /* count digits, white space, others */

 main()
 {
   int c, i, nwhite, nother;
   int ndigit[10];

   nwhite = nother = 0;

   for (i = 0; i < 10; ++i)
   {
       ndigit[i] = 0;
   }

   while ((c = getchar()) != EOF)
   {
     if (c >= '0' && c <= '9')
     {
         ++ndigit[c-'0'];
     }
     else if (c == ' ' || c == '\n' || c == '\t')
     {
         ++nwhite;
     }
     else
     {
         ++nother;
     }

   printf("digits =");

   for (i = 0; i < 10; ++i)
   {
      printf(" %d", ndigit[i]);
   }

   printf(", white space = %d, other = %d\n",nwhite, nother);
 }
#包括
/*计算数字、空白、其他*/
main()
{
int c,i,nwhite,other;
int-ndigit[10];
nwhite=nother=0;
对于(i=0;i<10;++i)
{
ndigit[i]=0;
}
而((c=getchar())!=EOF)
{

if(c>='0'&&c='0'&&cif
语句检查字符是否为数字,
++ndigit[c-'0']
语句更新该数字的计数。当
c
是介于
'0'
'9'
之间的字符时,则
c-'0'
是介于
0
9
之间的数字。换句话说,
'0'
的ASCII值是48位小数,
'1'
是49,
'2'
是50位,以此类推e> c-'0'与
c-48
相同,并将
48,49,50,…
转换为
0,1,2…

提高理解能力的一种方法是在代码中添加
printf
,例如替换

if (c >= '0' && c <= '9')
     ++ndigit[c-'0'];

如果(c>='0'&&c='0'&&c我会尝试用一个例子来解释

假设输入是abc12323

所以频率1=1

频率2=2

频率3=2

if (c >= '0' && c <= '9') //checks whether c is a  digit  
      ++ndigit[c-'0']; 

如果(c>='0'&&c)您误读了K&R或者他们有错误。我读取代码的方式是,如果c是一个数字,则增加相应的ndigit值。例如,如果c='7',则c-'0'='7'-'0'=7(因为数字的字符编码是连续的),因此代码将增加数字[7].Michael L,把它作为一个答案。@jimmcnamara这个练习的重点是自己编写isdigit函数。如果您满意,请将其中一个答案标记为已接受
if (c >= '0' && c <= '9') //checks whether c is a  digit  
      ++ndigit[c-'0'];