แบบฝึกหัด C/C++ สำหรับผู้เริ่มต้น

นับสระ

นับสระในข้อความหนึ่งบรรทัด

นับสระ คืออะไร?

การจำแนกตัวอักษรรวมการไล่ดู การปรับรูปแบบ และการตรวจว่าเป็นสมาชิกหรือไม่

ประเด็นสำคัญ

  • เปิด compiler warning และแก้ทุกคำเตือน
  • รู้ type และ lifetime ของทุกค่า
  • ตรวจ input และขอบเขต array ให้ชัดเจน

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
    const char *text = "Code Utility"; int count = 0;
    // strchr performs a compact membership check.
    for (; *text; ++text) if (strchr("aeiou", tolower((unsigned char)*text))) ++count;
    printf("vowels=%d\n", count);
}
ผลลัพธ์ที่คาดหวัง
vowels=5
C++
รันโค้ด →
main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
    std::string text = "Code Utility";
    // count_if counts characters accepted by the predicate.
    auto vowels = std::count_if(text.begin(), text.end(), [](unsigned char c) {
        return std::string("aeiou").find(std::tolower(c)) != std::string::npos;
    });
    std::cout << "vowels=" << vowels << '\n';
}
ผลลัพธ์ที่คาดหวัง
vowels=5

เปรียบเทียบ C และ C++

แปลงตัวอักษรแต่ละตัวเป็นตัวพิมพ์เล็กก่อนเทียบกับสระห้าตัว

C

C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน

C++

C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • เพิ่ม input ผิดและค่าขอบเขต
  • Compile ด้วย -Wall -Wextra -Wpedantic
  • แยก declaration และ implementation

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด