isspace() ตรวจสอบว่าเป็น Whitespace Character หรือไม่ (Space, Tab, Newline, Vertical Tab, Form Feed, Carriage Return) ประกาศใน <ctype.h>
ตัวอย่าง 1: นับ Space ใน String
#include <iostream>
#include <ctype.h>
using namespace std;
int main() {
char str[] = "Coding is fun";
int count = 0;
for (int i = 0; str[i] != '\0'; i++)
if (isspace(str[i]))
count++;
cout << "Number of spaces: " << count;
return 0;
}
ผลลัพธ์
Number of spaces: 2
ตัวอย่าง 2: ตรวจสอบตัวอักษรเดี่ยว
#include <iostream>
#include <ctype.h>
using namespace std;
int main() {
char ch1 = 'A';
char ch2 = ' ';
if (isspace(ch1)) cout << "ch1 is space\n"; else cout << "ch1 not space\n";
if (isspace(ch2)) cout << "ch2 is space\n"; else cout << "ch2 not space\n";
return 0;
}
ผลลัพธ์
ch1 not space
ch2 is space
Whitespace Characters ใน C
| Char | Escape | ASCII | ชื่อ |
|---|---|---|---|
| Space | ' ' | 32 | Space |
| \t | HT | 9 | Horizontal Tab |
| \n | LF | 10 | Line Feed |
| \v | VT | 11 | Vertical Tab |
| \f | FF | 12 | Form Feed |
| \r | CR | 13 | Carriage Return |
ข้อควรระวัง: ส่ง Argument เป็น unsigned char หรือ EOF เท่านั้น