標準入力からの入力に現れた数字をカウントする (ver.2)

明解C言語 入門編 > 8. いろいろなプログラムを作ってみよう >

標準入力からの入力に現れた数字をカウントする (ver.2)

C


#include <stdio.h>

int main(int argc, char* argv[])
{
int i, ch;
int cnt[10] = {0};

while ((ch = getchar()) != EOF)
{
if (('0' <= ch) && (ch <= '9'))
cnt[ch - '0']++;
}

for (i = 0; i < 10; i++)
{
printf("'%d' : %d\n", i, cnt[i]);
}

return 0;
}

実行結果


R:\>lesson066\Project1.exe
3.14159265
^Z
'0' : 0
'1' : 2
'2' : 1
'3' : 1
'4' : 1
'5' : 2
'6' : 1
'7' : 0
'8' : 0
'9' : 1

Delphi


program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;

procedure main();
var
i, j: Integer;
s: String;
cnt: array[0..9] of Integer;
begin
for i := 0 to 9 do
cnt[i] := 0;

while (not Eof) do
begin
readln(s);

for i := 0 to length(s) do
begin
if ('0' <= s[i]) and (s[i] <= '9') then
begin
j := Integer(s[i]) - Integer('0');
inc(cnt[j]);
end;
end;

end;

for i := 0 to 9 do
writeln(format('"%d" : %d', [i, cnt[i]]));
end;

begin
main;
end.

実行結果


S:\>lesson066\Project1.exe
3.14159265
^Z
"0" : 0
"1" : 2
"2" : 1
"3" : 1
"4" : 1
"5" : 2
"6" : 1
"7" : 0
"8" : 0
"9" : 1