C++サンプル集

【第1部】C言語(K&R検証)編

0006.数字、空白文字、その他をカウント

ソース紹介

CPPファイルに記述
#include <iostream>
#include <cstdio>
using namespace std;

/*
数字、空白文字、その他をカウント
*/
int main()
{
    int nwhite{};
    int nother{};
    int ndigit[10] {};
    char c;
    while ((c = cin.get()) != EOF) {
        if (c >= '0' && c <= '9') {
            ++ndigit[c - '0'];
        }
        else if (c == ' ' || c == '\n' || c == '\t') {
            ++nwhite;
        }
        else {
            ++nother;
        }
    }
    for (auto v: ndigit) {
        cout << v << ", ";
    }
    cout << "空白: " << nwhite << ", それ以外: " << nother << endl;
    return 0;
}
出力
2018-02-15 12:34:56
ABCDEFG abcdefg
1961-03-17 00:00:00
hello world
^Z
9, 6, 3, 2, 1, 2, 2, 1, 1, 1, 空白: 8, それ以外: 32

サンプル説明

 このサンプルは、C++11の新しい機能が結構盛り込まれています。
 まず初期化ですが、
    int nwhite{};
    int nother{};
    int ndigit[10] {};
 でnwhite、notherそしてndigit配列がすべて 0 に初期化されます。
 また、拡張for文も使用されています。
    for (auto v: ndigit) {
        cout << v << ", ";
    }
 また、C++11とは関係ありませんが
        if (c >= '0' && c <= '9') {
            ++ndigit[c - '0'];
        }
 はASCIIコード '0' から '9' まで順番に並んでいるから、記述できる手法です。

K&Rでの記述

 元になったのは第1章:やさしい入門に記述されています。配列の説明のところです。