Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน iscntrl() ใน C++

iscntrl() ตรวจสอบว่าตัวอักษรเป็น Control Character หรือไม่ (Non-printable, ไม่ใช่ Space) เช่น \n, \t, \r, Bell ประกาศใน <ctype.h>

รูปแบบ

int iscntrl(int ch);

ตัวอย่าง 1: นับ Control Characters ใน String

#include <iostream>
#include <ctype.h>
using namespace std;

int main() {
    char str[] = "Coding\tis\tfun\n";
    int count = 0;
    for (int i = 0; str[i] != '\0'; i++)
        if (iscntrl(str[i]))
            count++;
    cout << "Number of control characters: " << count;
    return 0;
}

ผลลัพธ์

Number of control characters: 3

(มี 2 tabs และ 1 newline)

ตัวอย่าง 2: ตรวจสอบตัวอักษรเดี่ยว

#include <iostream>
#include <ctype.h>
using namespace std;

int main() {
    char ch1 = 'A';
    char ch2 = '\n';
    if (iscntrl(ch1))
        cout << "ch1 is a control character\n";
    else
        cout << "ch1 is not a control character\n";
    if (iscntrl(ch2))
        cout << "ch2 is a control character\n";
    else
        cout << "ch2 is not a control character\n";
    return 0;
}

ผลลัพธ์

ch1 is not a control character
ch2 is a control character

Control Characters ใน ASCII (0-31 และ 127)

CodeCharName
0NULNull
7BELBell
8BSBackspace
9HTHorizontal Tab (\t)
10LFLine Feed (\n)
13CRCarriage Return (\r)
27ESCEscape
127DELDelete

หมายเหตุ: Space (32) ไม่ใช่ Control Character (ใช้ isspace() แทน)