Bài tập C/C++ cho người mới

Count Words

Bài tập nhập môn này giúp luyện cú pháp cốt lõi và tư duy giải quyết vấn đề qua Count Words.

Count Words là gì?

Bài tập nhập môn này giúp luyện cú pháp cốt lõi và tư duy giải quyết vấn đề qua Count Words.

Giải bài Count Words bằng cả C và C++ với code có thể chạy.

Điểm quan trọng

  • Luôn bật compiler warning và xử lý mọi cảnh báo.
  • Hiểu rõ type và lifetime của từng giá trị.
  • Kiểm tra input và giới hạn mảng rõ ràng.

Code ví dụ bằng C và C++

C
Chạy code →
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);
}
Output dự kiến
words=4
C++
Chạy code →
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';
}
Output dự kiến
words=4

So sánh C và C++

So sánh implementation C và C++, sau đó thay đổi input và kiểm tra thêm các edge case.

C

C dùng API thủ tục nhỏ gọn và thể hiện chi tiết biểu diễn rõ ràng.

C++

C++ giữ mô hình low-level nhưng bổ sung type thư viện và abstraction an toàn hơn.

Bài tập mở rộng

Chạy cả hai phiên bản rồi thay đổi để quan sát khác biệt về bảo đảm của từng ngôn ngữ.

  • Thêm input sai và boundary value.
  • Biên dịch với -Wall -Wextra -Wpedantic.
  • Tách declaration dùng lại vào header và implementation file.