初めての投稿になります。よろしくお願いします。
今、学校でc言語の学習をしています。「英文が書かれたファイルを読み込んで,ファイルに含まれる文の数を数える」プログラムを書きたいのですが、うまくいきません。文の数を判定する文字は'.''!''?'のどれかです。
例えば、1行分の英文が書かれたプログラムだと、うまくカウントされるのですが、2行以上の文章だと、余計にカウントされたり、逆に本来カウントされるべきところでされなかったりと、ぐちゃぐちゃです。おそらくwhile文の条件が間違っていると思いますが、どのように間違っているのか指摘していただけるとありがたいです。
#include <stdio.h> #include <stdlib.h> int main(void){ FILE *fp; char text_name[81], text[81]; int i=0, count; scanf("%s", text_name); fp=fopen(text_name, "r"); while(fgets(text, 81, fp)!=NULL){ while(text[i]!='\n'){ if(text[i]=='.' || text[i]=='?' || text[i]=='!'){ count++; } i++; } } printf("Number of sentences = %d\n", count); fclose(fp); return 0; }
テキスト1
Here is a sentence. Here is another one! Does your program work?
テキスト2
Here is a sentence. Here is one on another line. This is line three. And line 4.
回答3件
あなたの回答
tips
プレビュー