Count Vowels
この初心者向け演習では、Count Vowelsを通して基本構文と問題解決を練習します。
Count Vowelsとは?
この初心者向け演習では、Count Vowelsを通して基本構文と問題解決を練習します。
Count VowelsをCとC++の実行可能なコードで解きます。
重要なポイント
- compiler warningを有効にしてすべて修正します。
- 各値の型とlifetimeを把握します。
- 入力と配列の境界を検証します。
CとC++のコード例
C
main.c
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "Code Utility"; int count = 0;
// strchr performs a compact membership check.
for (; *text; ++text) if (strchr("aeiou", tolower((unsigned char)*text))) ++count;
printf("vowels=%d\n", count);
}
vowels=5
C++
main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string text = "Code Utility";
// count_if counts characters accepted by the predicate.
auto vowels = std::count_if(text.begin(), text.end(), [](unsigned char c) {
return std::string("aeiou").find(std::tolower(c)) != std::string::npos;
});
std::cout << "vowels=" << vowels << '\n';
}
vowels=5
CとC++の比較
CとC++の実装を比較し、入力を変更して追加の境界ケースをテストしてください。
C
Cは小さな手続き型APIと表現の詳細を明示します。
C++
C++は低レベルモデルを保ちつつ安全な型を追加します。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- 不正入力と境界値を追加します。
- -Wall -Wextra -Wpedanticでコンパイルします。
- 宣言と実装を分割します。