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

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

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

CharEscapeASCIIชื่อ
Space' '32Space
\tHT9Horizontal Tab
\nLF10Line Feed
\vVT11Vertical Tab
\fFF12Form Feed
\rCR13Carriage Return

ข้อควรระวัง: ส่ง Argument เป็น unsigned char หรือ EOF เท่านั้น