Count Words
この初心者向け演習では、Count Wordsを通して基本構文と問題解決を練習します。
Count Wordsとは?
この初心者向け演習では、Count Wordsを通して基本構文と問題解決を練習します。
Count WordsをCとC++の実行可能なコードで解きます。
重要なポイント
- compiler warningを有効にしてすべて修正します。
- 各値の型と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でコンパイルします。
- 宣言と実装を分割します。