초보자를 위한 C/C++ 연습

Count Words

이 초보자 연습은 Count Words을 통해 핵심 문법과 문제 해결을 훈련합니다.

Count Words이란?

이 초보자 연습은 Count Words을 통해 핵심 문법과 문제 해결을 훈련합니다.

Count Words 문제를 C와 C++의 실행 가능한 코드로 해결합니다.

중요한 점

  • Compiler warning을 켜고 모두 해결하세요.
  • 각 값의 type과 lifetime을 파악하세요.
  • 입력과 배열 경계를 검증하세요.

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++ 비교

C와 C++ 구현을 비교하고 입력을 바꾼 뒤 추가 경계 사례를 테스트하세요.

C

C는 작은 절차형 API와 표현 세부 사항을 드러냅니다.

C++

C++는 저수준 모델을 유지하며 더 안전한 타입을 추가합니다.

연습 문제

두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.

  • 잘못된 입력과 경계값을 추가하세요.
  • -Wall -Wextra -Wpedantic으로 컴파일하세요.
  • 선언과 구현을 분리하세요.