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

ฟังก์ชัน isgraph() ใน C: ตรวจสอบกราฟิกตัวอักษร

ฟังก์ชัน isgraph() ตรวจสอบว่าตัวอักษรมี Graphical Representation (รูปแบบที่มองเห็นได้/พิมพ์ได้) หรือไม่ อยู่ใน Header <ctype.h>

ไวยากรณ์

#include <ctype.h>
int isgraph(int c);
  • Parameter: int c - ตัวอักษรที่จะตรวจสอบ (ส่งเป็น unsigned char หรือ EOF)
  • คืนค่า: Non-zero (True) ถ้ามี Graphical Representation, 0 (False) ถ้าไม่มี

ตัวอย่าง

#include <stdio.h>
#include <ctype.h>

int main() {
    int a = '\n';  // Newline - Control Character
    int b = '8';   // Digit - Graphical
    int c = 's';   // Letter - Graphical
    
    if (isgraph(a))
        printf("'\\n' has graphical representation\n");
    else
        printf("'\\n' has NO graphical representation\n");
    
    if (isgraph(b))
        printf("'8' has graphical representation\n");
    else
        printf("'8' has NO graphical representation\n");
    
    if (isgraph(c))
        printf("'s' has graphical representation\n");
    else
        printf("'s' has NO graphical representation\n");
    
    return 0;
}

ผลลัพธ์

'\n' has NO graphical representation
'8' has graphical representation
's' has graphical representation

ตัวอักษรที่ isgraph() คืน True

ทุกตัวอักษรที่พิมพ์ได้ ยกเว้น Space (' '):

  • ตัวอักษร: A-Z, a-z
  • ตัวเลข: 0-9
  • Punctuation: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~

ตัวอักษรที่ isgraph() คืน False

  • Space (' ') - Printable แต่ไม่ Graphical
  • Control Characters: \n, \t, \r, \v, \f, \b, \0 (ASCII 0-31, 127)
  • EOF (-1)

ความแตกต่าง: isgraph() vs isprint()

ฟังก์ชันSpace (' ')Letters/Digits/PunctControl Chars
isgraph()False (0)TrueFalse
isprint()TrueTrueFalse

ฟังก์ชันในกลุ่ม ctype.h ที่เกี่ยวข้อง

ฟังก์ชันตรวจสอบ
isalnum()Alphanumeric (A-Z, a-z, 0-9)
isalpha()Alphabetic (A-Z, a-z)
isdigit()Decimal Digit (0-9)
isxdigit()Hex Digit (0-9, A-F, a-f)
islower()Lowercase (a-z)
isupper()Uppercase (A-Z)
isspace()Whitespace (Space, \t, \n, \v, \f, \r)
iscntrl()Control Characters
ispunct()Punctuation (Printable but not Alphanumeric/Space)
isprint()Printable (Graphical + Space)
isgraph()Graphical (Printable - Space)

ข้อควรระวัง: Undefined Behavior

// ผิด: ส่ง char โดยตรง (อาจเป็น signed char → negative values)
char ch = getchar();
isgraph(ch);  // UB ถ้า ch < 0

// ถูกต้อง: Cast เป็น unsigned char
isgraph((unsigned char)ch);

// หรือใช้ int ตรงๆ
int ch = getchar();
isgraph(ch);  // Safe: int รองรับ EOF และ unsigned char ทั้งหมด

สรุป

isgraph() ตรวจสอบ "Printable และไม่ใช่ Space" ใช้สำหรับ Validate Input, Parsing, Text Processing ต้อง Cast เป็น unsigned char เพื่อความปลอดภัย