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

Count Words

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

Count Words คืออะไร?

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

แก้โจทย์ Count Words ด้วย code C และ C++ ที่รันได้

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

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

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

C
รันโค้ด →
main.c
#include <ctype.h>
#include <stdio.h>
int main(void) {
    const char *text = "C and C++ examples"; int words = 0, inside = 0;
    // Count transitions from whitespace into a word.
    for (; *text; ++text) { if (isspace((unsigned char)*text)) inside = 0; else if (!inside) { ++words; inside = 1; } }
    printf("words=%d\n", words);
}
ผลลัพธ์ที่คาดหวัง
words=4
C++
รันโค้ด →
main.cpp
#include <iostream>
#include <sstream>
#include <string>
int main() {
    std::istringstream input("C and C++ examples"); std::string word; int words = 0;
    // Formatted extraction skips whitespace and returns one word.
    while (input >> word) ++words;
    std::cout << "words=" << words << '\n';
}
ผลลัพธ์ที่คาดหวัง
words=4

เปรียบเทียบ 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