Search code examples
cgetchar

How to get the latest value in getchar()?


i am entering input using getchar() function and when i press the enter after entering the input i get the value of c inside loop as good which i entered but when i enter a non-digit and the loop breaks ... the latest value of i entered is a new line which has ASCII value as 10.

how could i possibly retain the digit value . All i want is c to have the digit value after the loop breaks

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

Solution

  • One way todo this is to add a lag variable and write to this from c every iteration :

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