ファイル操作の問題なのですが、どこが間違っているのかわかりません(><)
問題
適当な英文ファイルを読み込んで, アルファベット a ~ z の各文字の出現回数をファイル frequency.txt に出力するプログラムを作成せよ. ただし, 大文字と小文字は区別しないものとする.
※ fgets で文字列にデータを一行づつ読み込み, 文字列中の文字を一文字づつ調べて出現回数を配列に記録することにより数えよ. 例えば, 配列を int count[26] とすると, 'a' の個数を count[0] で, 'b' の個数を count[1] で, …, 'z' の個数を count[25] で数えるようにすればよい.
下記の英文をファイルに保存して実行し,
Great spirits have always encountered opposition from mediocre minds.
The mediocre mind is incapable of understanding the man who refuses to bow
blindly to conventional prejudices and chooses instead to express
his opinions courageously and honestly.
a: 13 b: 3 c: 8 d: 12 e: 24
f: 3 g: 3 h: 7 i: 18 j: 1
k: 0 l: 7 m: 6 n: 20 o: 22
p: 7 q: 0 r: 11 s: 19 t: 13
u: 6 v: 2 w: 3 x: 1 y: 4
z: 0
が得られることを確認せよ.
プログラム
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
int i; int count[26]; FILE *fpin,*fpout; char c[100]; char s; if((fpin = fopen("indata.txt","r"))==NULL) { printf("ファイルが見つかりません---indata.txt\n"); exit(EXIT_FAILURE); } if((fpout = fopen("frequency.txt","w"))==NULL) { printf("ファイルが見つかりません---frequency.txt\n"); exit(EXIT_FAILURE); } for(i=0; i<26; i++) count[i]=0; while(fgets(c,100,fpin)) { for(i=0; i<strlen(c); i++) { s=c[i]; if(s>'a' && s<'z') count[s-'a']++; if(s>'A' && s<'Z') count[s-'A']++; } } for(i=0; i<26; i++) { fprintf(fpout,"%c:%d\n",'a'+i,count[i]); } fclose(fpin); fclose(fpout); return EXIT_SUCCESS;
}
結果
a:0
b:3
c:8
d:12
e:24
f:3
g:3
h:7
i:18
j:1
k:0
l:7
m:6
n:20
o:22
p:7
q:0
r:11
s:19
t:13
u:6
v:2
w:3
x:1
y:4
z:0
長文失礼しました。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。