isprint() Function Example in C Programming

In this source code example, we will see how to use the isprint() function in C programming with an example.

isprint() Function Overview

The isprint() function is part of the <ctype.h> library in C. It checks whether a given character is printable. Printable characters are those characters that are not control characters; i.e., they have a visible representation. 

Key Points: 

- To use the isprint() function, include the <ctype.h> header. 

- The function takes an int as an argument, representing the ASCII value of the character. 

- It returns a non-zero integer if the character is printable, otherwise it returns 0.

Source Code Example

#include <stdio.h>
#include <ctype.h> // Required for isprint()

int main() {
    char ch;

    printf("Enter a character: ");
    scanf("%c", &ch);

    if (isprint(ch)) {
        printf("The character '%c' is printable.\n", ch);
    } else {
        printf("The character '%c' is not printable.\n", ch);
    }

    return 0;
}

Output

Enter a character: A
The character 'A' is printable.
Enter a character: \n
The character '\n' is not printable.

Explanation

1. We include the required header files: stdio.h for standard input/output and ctype.h for the isprint() function.

2. In the main() function, we declare a character variable ch.

3. We prompt the user to enter a character and store it in ch.

4. We then use isprint() to determine if the entered character is printable.

5. Finally, based on the result, we print a message to the console indicating whether the character is printable or not.

This covers the basic usage and functionality of the isprint() function in C. It's useful when you need to validate user input or when parsing text.


Comments