นับคำ
นับคำที่คั่นด้วยช่องว่างในประโยค
นับคำ คืออะไร?
การนับคำฝึกการเปลี่ยนสถานะขณะไล่ดูข้อความ
ประเด็นสำคัญ
- เปิด compiler warning และแก้ทุกคำเตือน
- รู้ type และ lifetime ของทุกค่า
- ตรวจ input และขอบเขต array ให้ชัดเจน
ตัวอย่างโค้ด 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++
นับหนึ่งคำเมื่ออักขระที่ไม่ใช่ช่องว่างตามหลังจุดเริ่มต้นหรือตามหลังช่องว่าง
C
C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน
C++
C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เพิ่ม input ผิดและค่าขอบเขต
- Compile ด้วย -Wall -Wextra -Wpedantic
- แยก declaration และ implementation
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด