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

Count Vowels

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Count Vowels

Count Vowels คืออะไร?

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Count Vowels

แก้โจทย์ Count Vowels ด้วย code 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++

เปรียบเทียบ implementation ของ C และ C++ จากนั้นเปลี่ยน input และทดสอบ edge case เพิ่มเติม

C

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

C++

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

แบบฝึกหัด

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

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