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

การทำงานของ isprint() ใน C++

บทนำ

isprint() ใน C++ เป็นฟังก์ชันในตัว (Built-in) ใน header file "cctype.h" ซึ่งตรวจสอบว่าตัวอักษรเป็นตัวอักษรที่พิมพ์ได้ (Printable) หรือไม่

isprint คืนค่า true สำหรับตัวอักษรคงที่ นอกจากอักขระช่องว่าง (' ') ที่คืนค่า true

มีรุ่นเฉพาะ locale ของฟังก์ชันนี้ (isprint) อยู่ใน header cctype

  • isprint() ใช้ตรวจสอบอักขระที่ไม่พิมพ์ได้ (Non-Printing) ในชุดประโยค
  • isprint() เป็นฟังก์ชันในตัวที่ให้วิธีจัดการอักขระไม่พิมพ์ได้อย่างมีประสิทธิภาพ
  • isprint() ช่วยลดจำนวนบรรทัดโค้ดสำหรับโปรแกรมเมอร์
  • isprint() ลดเวลาคอมไพล์ของโปรแกรมได้จริง

การ include cctype.h ไม่เพียงแต่ให้ใช้ isprint() แต่ยังปลดล็อกฟังก์ชันที่เกี่ยวข้องอีกมากมาย เช่น:

  • isblank (ตรวจสอบช่องว่าง)
  • iscntrl (ตรวจสอบ Control Character)
  • isdigit (ตรวจสอบตัวเลข)
  • isgraph (ตรวจสอบมีการแสดงผลกราฟิกหรือไม่)

Syntax

Int isprint (int c);

"อักขระที่พิมพ์ได้ (Printable character) คืออักขระที่ครอบครองตำแหน่งการพิมพ์บนหน้าจอ"

Parameters

c คือตัวอักษรที่จะตรวจสอบ แปลงเป็น int หรือ EOF

ตัวอย่าง

Input: first line \n second line \n
Output: first line

Input: line one \n line two\n line three \n
Output: line one

คำอธิบาย - จะพิมพ์แค่บรรทัดแรกเพราะอักขระ newline (\n) ไม่ใช่ printable character

ตัวอย่างโค้ด

/* isprint example */
#include <stdio.h>
#include <ctype.h>
int main () {
    int i = 0;
    char str[] = "first line n second line n";
    while (isprint(str[i])) {
        putchar (str[i]);
        i++;
    }
    return 0;
}

ผลลัพธ์

first line n second line n

ตัวอย่างเพิ่มเติม

#include <cctype>
#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char str[] = "Hellotallnhow are you";
    for (int i = 0; i < strlen(str); i++) {
        if (!isprint(str[i]))
            str[i] = ' ';
    }
    cout << str;
    return 0;
}

ผลลัพธ์

Hellotallnhow are you

คำอธิบาย

ตัวอย่างที่สอง แทนที่อักขระ non-printable ด้วยช่องว่าง แล้วพิมพ์สตริงทั้งหมด