'Converting and printing Decimal of a char in C
After reading a single character as input, how do I determine what type of character it is? For example, how do I determine whether the character is a number, a letter or a dot?
Solution 1:[1]
You can use
- the function
isdigitto determine whether a character is a digit, - the function
isalphato determine whether a character is an alphabetic letter, - the function
ispunctto determine whether a character is a punctuation mark, - the function
isspaceto determine whether a character is a whitespace character.
You can find a full list of all character classification functions of the C standard library here.
If you want to restrict the comparison to "a dot" (i.e. not any punctuation mark), then you can compare the value of the character directly with '.'.
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int c;
printf( "Please enter a single character: " );
c = getchar();
if ( isdigit( c ) )
{
printf( "The input is a digit.\n" );
}
else if ( isalpha( c ) )
{
printf( "The input is an alphabetical letter.\n" );
}
else if ( c == '.' )
{
printf( "The input is a dot.\n" );
}
else if ( ispunct( c ) )
{
printf( "The input is a punctuation character.\n" );
}
else if ( isspace( c ) )
{
printf( "The input is a whitespace character.\n" );
}
else
{
printf( "The input is not a digit, letter, punctuation or whitespace character.\n" );
}
}
This program has the following behavior:
Please enter a single character: j
The input is an alphabetical letter.
Please enter a single character: 7
The input is a digit.
Please enter a single character: .
The input is a dot.
Please enter a single character: ;
The input is a punctuation character.
Please enter a single character:
The input is a whitespace character.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
