ฟังก์ชัน iscntrl() ใน C++ จะตรวจสอบว่าอักขระเป็นอักขระควบคุมหรือไม่ ฟังก์ชันนี้กำหนดเป็น ctype.h.
ไวยากรณ์สำหรับฟังก์ชัน iscntrl() ถูกกำหนดดังนี้ −
int iscntrl ( int ch );
ในที่นี้ ch คืออักขระที่ต้องตรวจสอบ
โปรแกรมที่แสดงฟังก์ชัน iscntrl() โดยการนับจำนวนอักขระควบคุมในสตริงจะได้รับดังนี้ -
ตัวอย่าง
#include <iostream>
#include <ctype.h>
using namespace std;
int main() {
char str[] = "Coding\tis\tfun\n";
int i, count = 0;
for(i=0; str[i]!='\0';i++) {
if(iscntrl(str[i]))
count++;
}
cout<<"Number of control characters in the string are "<<count;
return 0;
} ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นเป็นดังนี้ −
Number of control characters in the string are 3
ในโปรแกรมข้างต้น ขั้นแรกให้กำหนดสตริง จากนั้นใช้ for loop เพื่อตรวจสอบอักขระแต่ละตัวในสตริงเพื่อดูว่าเป็นอักขระควบคุมหรือไม่ หากเป็นเช่นนั้น การนับจะเพิ่มขึ้น 1 ในที่สุด ค่าของการนับจะปรากฏขึ้น ซึ่งแสดงอยู่ในตัวอย่างโค้ดต่อไปนี้ −
char str[] = "Coding\tis\tfun\n";
int i, count = 0;
for(i=0; str[i]!='\0';i++) {
if(iscntrl(str[i]))
count++;
}
cout<<"Number of control characters in the string are "<<count; นี่เป็นอีกโปรแกรมหนึ่งที่แสดงฟังก์ชัน iscntrl() ระบุว่าอักขระที่กำหนดเป็นอักขระควบคุมหรือไม่ โปรแกรมจะได้รับดังนี้ −
ตัวอย่าง
#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"<<endl;
else
cout<<"ch1 is not a control character"<<endl;
if(iscntrl(ch2))
cout<<"ch2 is a control character"<<endl;
else
cout<<"ch2 is not a control character"<<endl;
return 0;
} ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นเป็นดังนี้ −
ch1 is not a control character ch2 is a control character
ในโปรแกรมข้างต้น มีการกำหนด ch1 และ ch2 จากนั้นใช้ iscntrl() เพื่อตรวจสอบว่าเป็นอักขระควบคุมหรือไม่ ข้อมูลโค้ดสำหรับสิ่งนี้จะได้รับดังนี้ −
char ch1 = 'A'; char ch2 = '\n'; if(iscntrl(ch1)) cout<<"ch1 is a control character"<<endl; else cout<<"ch1 is not a control character"<<endl; if(iscntrl(ch2)) cout<<"ch2 is a control character"<<endl; else cout<<"ch2 is not a control character"<<endl;