Search code examples
cchargetchar

printf format character from getchar() in C


I have a task is to print the ASCII code number and the input: Below is my code:

#include <stdio.h>

int main(void){
  char ch;
  printf("Whatever: ");
  while((ch = getchar()) != 'q')
  {
    getchar();
    printf("The char is %c and %d in ASCII.\n", ch, ch);
  }

  return 0;
}

What should I revise if I want to print the \n from the getchar() function?

Example: 
  The char is \n and 10 in ASCII.

Solution

  • Hope below helps

    while((ch = getchar()) != 'q')
    {
       if(ch == '\n')
            printf("The '\\n' ascii value is %d\n", ch);
       else
            printf("The '%c' ascii value is %d\n", ch, ch);
    }