A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
iscntrl returns nonzero for control characters: ASCII 0 through 31, plus 127 (DEL). These are the non-printing characters that terminal emulators interpret as commands: newline, tab, escape, bell, backspace. In data processing, unexpected control characters indicate corruption, injection attempts, or binary data masquerading as text. Detecting them is the first step in sanitizing untrusted input.
#include <stdio.h>#include <ctype.h>int count_control_chars(const char *s, size_t len) {int count = 0;for (size_t i = 0; i < len; i++) {if (iscntrl((unsigned char)s[i])) {count++;}}return count;}int main(void) {const char *clean = "Hello, World!";const char *dirty = "Hello\x07\x1B[31mWorld\x00";printf("Clean: %d control chars\n",count_control_chars(clean, 13));printf("Dirty: %d control chars\n",count_control_chars(dirty, 15));return 0;}
The dirty string contains a bell (0x07), an escape (0x1B), and a null (0x00), plus the characters that form the ANSI sequence. iscntrl flags the non-printing ones. In a security context, an unexpected escape character in user input could be a terminal injection attempt. An unexpected null could truncate a string in a C-based backend. Detect and reject.
iscntrl is the inverse of isprint (roughly). Where isprint says "safe to display," iscntrl says "this is a control signal." Use it to validate that text input does not contain terminal escape sequences, null bytes, or other characters that could confuse downstream processing. Next: isgraph, the printable test that excludes space.
Finish the lesson once you have worked through the material. This awards ★ 10 XP.