【第1部】C言語(K&R検証)編
0017.数字、空白文字、その他をカウント(switch版)
ソース紹介
ここでは
0006.数字、空白文字、その他をカウントのサンプルを
switch文を使って書き直したものです。
CPPファイルに記述
#include <iostream>
#include <cstdio>
using namespace std;
/*
数字、空白文字、その他をカウント(switch版)
*/
int main()
{
int i{}, nwhite{}, nother{}, ndigit[10]{};
char c;
while ((c = cin.get()) != EOF) {
switch (c) {
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
++ndigit[c - '0'];
break;
case ' ': case '\n': case '\t':
++nwhite;
break;
default:
++nother;
break;
}
}
for (auto v : ndigit) {
cout << v << ", ";
}
cout << "空白: " << nwhite << ", それ以外: " << nother << endl;
return 0;
}
出力
2019-10-27 12:34:56
ABCDEFG abcdefg
1961-03-17 00:00:00
hello world
^Z
9, 6, 3, 2, 1, 1, 2, 2, 0, 2, 空白: 8, それ以外: 32
サンプル説明
ここでポイントとなるのは
switch (c) {
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
++ndigit[c - '0'];
break;
//以下略
}
のところですね。
数字だった場合の部分を
caseで羅列しています。
K&Rでの記述
元になったのは
第3章:制御の流れに記述されています。
Switchの説明のところです。