C input/output operation

www.la‮tu‬turi.com
C input/output operation

input character

To read a single character as input, we use the 'getchar()' function.

In the following example, we take a character as the user's input and print the ASCII code for that character.

#include <stdio.h>
int main(void)
{
  char ch;
  printf("Enter any character: ");
  ch = getchar();
  printf("Entered character: %c\n", ch);
  printf("ASCII value: %d\n", ch);
  return 0;
}
Enter any character: A
Entered character: A
ASCII value: 65

Output character

To print a single character, we use the 'putchar()' function.

In the example below, we take a single character as input and output it using the putchar() function.

#include <stdio.h>
int main(void)
{
  char ch;
  printf("Enter any character: ");
  ch = getchar();
  printf("Entered character: ");
  putchar(ch);
  return 0;
}
Enter any character: A
Entered character: A

Test the character

We can test the characters using the 'ctype.h' header file in the C library.

Here are some functions from the ctype.h file that you can use to test characters.

functiondesc
isalnum (c)check if c is an alphanumeric character
isalpha (c)check if c is an alphabetic character
isdigit (c)check if c is a number
islower (c)check if is a lowercase letter
isprint (c)check if c is a printable character
ispunct (c)check if c is a punctuation
isspace (c)check if c is a space character
isupper (c)check if c is a capital letter

Write a program in C to take the user's character input and then check if it is a number

#include <stdio.h>
#include <ctype.h>
int main(void)
{
  char ch;
  printf("Enter character: ");
  ch = getchar();
  if (isdigit(ch)) {
    printf("Entered character is a digit.");
  }
  else {
    printf("Entered character is not digit.");
  }
  return 0;
}
Enter character: 6
Entered character is a digit.

In the above code, we use the 'if-else' condition.
Therefore, if 'isdigit(ch)' returns a non-zero value, then the if-block 'printf(" Entered character is a digit "entered. ); '.
Otherwise, the else block printf(" Entered character not digit") is executed; .

Created Time:2017-08-22 15:31:46  Author:lautturi