iscntrl() kiểm tra ký tự có phải control character (ký tự điều khiển) không. Định nghĩa trong <ctype.h> / <cctype>.
Control Character là gì?
Ký tự không in được, dùng để điều khiển thiết bị: \n (newline), \t (tab), \r (carriage return), \b (backspace), \f (form feed), \v (vertical tab), \a (bell), ESC, NULL...
ASCII: 0-31 và 127 (DEL).
Cú pháp
int iscntrl(int ch);
Tham số: int (ký tự cast sang unsigned char hoặc EOF)
Trả về: khác 0 nếu là control char, 0 nếu không.
Ví dụ 1: Đếm control character trong string
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char str[] = "Coding\tis\tfun\n"; // Chứa 2 tab + 1 newline
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (iscntrl((unsigned char)str[i])) count++;
}
cout << "Số control character: " << count << endl; // 3
return 0;
}
Kết quả
Số control character: 3
Ví dụ 2: Kiểm tra ký tự đơn lẻ
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char ch1 = 'A';
char ch2 = '\n';
cout << "ch1 ('A'): " << (iscntrl(ch1) ? "control" : "not control") << endl;
cout << "ch2 ('\\n'): " << (iscntrl(ch2) ? "control" : "not control") << endl;
return 0;
}
Kết quả
ch1 ('A'): not control
ch2 ('\n'): control
Các control character phổ biến
| Ký tự | Escape | ASCII | Tên |
|---|---|---|---|
| NULL | \0 | 0 | Null terminator |
| Bell | \a | 7 | Alert/Beep |
| Backspace | \b | 8 | Backspace |
| Tab | \t | 9 | Horizontal tab |
| Newline | \n | 10 | Line feed |
| Vertical tab | \v | 11 | Vertical tab |
| Form feed | \f | 12 | Form feed |
| Carriage return | \r | 13 | Carriage return |
| Escape | \e (GCC) / \033 | 27 | ESC |
| DEL | - | 127 | Delete |