###前提・実現したいこと
お世話になります。
英文の入力をstrtok によって切り出された単語の文字数のカウントを行うプログラムを書いてみたのですが、クラッシュしてしまいます。
例えば
”This is a pen.”
に対して、単語順にカウントしていき、
This 4 is 2 a 1 pen 3
の様にカウントしたいのですが、できません。
切り出された単語に対してstrlen を呼び出す際にクラッシュしているようですが、理由がわかりません。
strlenについて調べてみたところ、引数に文字配列のポインタをとる関数、ということなので使い方は間違っていないと思うのですが、上手くいきません。
どんなことでも構いませんのでご助言よろしくお願いします。
###入力ファイル
input.dat
In computer science, the dining philosophers problem is an example problem often used in concurrent algorithm design to illustrate synchronization issues and techniques for resolving them. It was originally formulated in 1965 by Edsger Dijkstra as a student exam exercise, presented in terms of computers competing for access to tape drive peripherals. Soon after, Tony Hoare gave the problem its present formulation.
###ソースコード
C
1#include <stdio.h> 2#include <stdlib.h> 3#include <string.h> 4#define N 256 //一行の最大長,255文字以下と想定 5 6int main(void){ 7 8 FILE *fp; 9 char *filename="input.dat"; //入力ファイル名 10 char readline[N]; //1行分の読み込みを代入 11 char *word; //strtokによって切り取られた1単語分 12 13 //ファイルが開けない場合の処理 14 if((fp=fopen(filename,"r"))==NULL){ 15 fprintf(stderr,"%s is not available.",filename); 16 exit(EXIT_FAILURE); 17 } 18 19 while((fgets(readline,N,fp))!=NULL){ //1行ずつreadlineへ読み込む 20 21 //読み込んだ1行を空白で区切っていく 22 word=strtok(readline," "); //1回目のstrtok 23 puts(word); 24 25 while(word!=NULL){ 26 word=strtok(NULL," "); //2回目のstrtok 27 puts(word); 28 printf("%d\n",strlen(word)); //文字数カウント, この行がクラッシュの原因 29 } 30 } 31 32 return 0; 33}
問題の1行を以下のコードに書き換え、終端文字'\0'までカウントする事も試してみましたが、同様にクラッシュしてしまいました。
C
1for(i=0;*(word+i)!='\0';i++){ 2} 3printf("%d",i);
###原因となる行を削除した場合の出力結果
単語ごとに切り出されるところまでは順調のようです。
In computer science, the dining philosophers problem is an example problem often used in concurrent algorithm design to illustrate synchronization issues and techniques for resolving them. It was originally formulated in 1965 by Edsger Dijkstra as a student exam exercise, presented in terms of computers competing for access to tape drive peripherals. Soon after, Tony Hoare gave the problem its present formulation.
###補足情報
MinGW
Eclipse Cpp Mars
Windows 10
回答3件
あなたの回答
tips
プレビュー