iscntrl() Function Example in C Programming

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

iscntrl() Function Overview

The iscntrl() function determines if the given character is a control character, which are non-printable character with ASCII values less than 32 plus the DEL character (127).

Key Points: 

- To utilize the iscntrl() function, include the <ctype.h> header. 

- The function receives an int (generally interpreted as a character) as its argument. 

- It returns a non-zero value (true) if the character is a control character; otherwise, it returns 0 (false).

Source Code Example

#include <stdio.h>
#include <ctype.h>

int main() {
    char ch;

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

    if (iscntrl(ch))
        printf("'%c' is a control character.\n", ch);
    else
        printf("'%c' is not a control character.\n", ch);

    return 0;
}

Output

Enter a character: [CTRL + J]
'\n' is a control character.

Explanation

1. The necessary header files are included first: stdio.h for input/output tasks and ctype.h for character-related functions.

2. In the main() function, a character variable ch is initialized.

3. The user is prompted to input a character.

4. We employ the iscntrl() function to ascertain if the inputted character is a control character.

5. Depending on the outcome of the function, the program outputs an appropriate message. Keep in mind that inputting a control character might require specific key combinations, such as CTRL + J for the newline character.


Comments