如何获取getchar()中的最新值?

时间:2015-04-18 05:21:46

标签: c getchar

我正在使用getchar()函数输入输入,当我在输入输入后按Enter键时,我得到了循环中c的值,这是我输入的,但是当我输入一个非数字并且循环中断时。 ..输入的i的最新值是new line,其ASCII值为10.

我怎么可能保留数字值。我想要的只是c在循环中断后具有数字值

#include<stdio.h>
#include<ctype.h>
main()
{
  int c =0;
  while(isdigit(c=getchar()))
  {
    printf("c is : %c\n",c);
  }
   printf("latest value of c(ASCII) is : %d\n",c);
}

2 个答案:

答案 0 :(得分:1)

这样做的一种方法是添加滞后变量并在每次迭代时从c写入:

#include<stdio.h>
#include<ctype.h>
int main(int argc, char *argv[])
{
  int c = '0', lastchar = 0;
  while(isdigit(c))
  {
    if(!lastchar)
    {   
      printf("c is : %c\n",c);
    }   
    lastchar = c;
    c = getchar();
  }
  printf("latest value of c(ASCII) is : %d\n",lastchar);
  return 0;
}

答案 1 :(得分:0)

#include<stdio.h>
#include<ctype.h>
int main()
{
  int c = 0, last = 0;
  while(isdigit(c=getchar()))
  {
    printf("c is : %c\n",c);
    last = c;
  }
   if (!last)
          printf("latest value of c(ASCII) is : %d\n", last);
   else
          printf("No digits were entered\n");
   return 0;
}

你可以这样做。

相关问题