C Programming
In this tutorial we will learn to handle character input output operations in C programming language.
So far we have learned about data types, tokens and variables in C programming language. Now lets talk about how to take user input in our program and then return some output.
To read a single character as input we use the getchar()
function.
In the following example we will take a character as input from the user and will print the ASCII code of the 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;
}
Output
Enter any character: A
Entered character: A
ASCII value: 65
To output a single character we use the putchar()
function.
In the following example we take a single character as input and then output it using putchar()
function.
#include <stdio.h>
int main(void)
{
char ch;
printf("Enter any character: ");
ch = getchar();
printf("Entered character: ");
putchar(ch);
return 0;
}
Output
Enter any character: A
Entered character: A
We can use the ctype.h
header file from the C library to perform tests on characters.
Following are some of the functions from the ctype.h
file that we can use to test characters.
All the given functions will return non-zero (true) value if the condition is satisfied by the passed argument c. If the condition fails then we will get zero (false).
Function | Description |
---|---|
isalnum(c) | Is c an alphanumeric character? |
isalpha(c) | Is c an alphabetic character? |
isdigit(c) | Is c a digit? |
islower(c) | Is c lower case letter? |
isprint(c) | Is c a printable character? |
ispunct(c) | Is c a punctuation mark? |
isspace(c) | Is c a white space character? |
isupper(c) | Is c upper case letter? |
We will first take the character as input using the getchar()
function then we will use the isdigit()
function to check if the entered character is a digit. If the function returns non-zero value then the character is a digit else it is not.
#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;
}
Output
Enter character: 6
Entered character is a digit.
In the above code we are using if-else
conditional statement. So, if isdigit(ch)
returns non-zero value then the code inside the if-block printf("Entered character is a digit.");
will be executed. Otherwise the else-block printf("Entered character is not digit.");
will be executed.
We will learn more about if-else statement in the later tutorial.
ADVERTISEMENT