Trusted answers to developer questions

What are isdigit() and ispunct() functions in C?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

isdigit()

The isdigit() function falls under the header file ctype.h.

Header file :

#include<ctype.h>

This function accepts a character and classifies the character as a digit. It returns a value other than 0 to indicate success. The isdigit() function checks if the character is a numeric characterin between 0 to 9. Although isdigit() accepts an integer as an argument, when a character is passed to the function it internally converts the character to an ASCII value.

Syntax:

int isdigit(int a);

Here, a is the character to be checked.

Note: If the character passed as argument in isdigit() function is a digit, a non zero value is returned. If the character passed as argument in the isdigit() function is not a digit, 0 is returned.

Code

Below is a simple program that checks to see if it is a digit:

#include <stdio.h>
#include<ctype.h>
int main()
{ char ch='8';
if(isdigit(ch))
{
printf("condition is true");
}
else
{
printf("condition is false");
}
}

ispunct()

The ispunct() function falls under the ctype.h header file.

Header file :

#include<ctype.h>

The ispunct() function is used to determine if a character is a punctuation mark.

Syntax:

int ispunct(int argument);

If the character passed to the ispunct() function is punctuation, then a non-zero integer is returned. If not, it returns 0.

Code

The program below checks for punctuation in a sentence:

#include <stdio.h>
#include <ctype.h>
int main()
{
char str[] = "Alas!, You have won the prize. ";
int i = 0, value=0;
while (str[i]) { //iterating through the string
if (ispunct(str[i])) //checking the condition
value++;
i++;
}
printf("The sentence has %d punctuation"
" characters.\n", value);
return 0;
}

RELATED TAGS

Did you find this helpful?