標準入力から入力した文字とファイルから読み込んだ文字を比較してCtrl+Dを入力したらループを抜け出せるものを作っていたのですが、このコードだと抜け出せるものの実行結果が次のようになってしまいます。自分はこれでいけると思っていたので何を直せばいいのかわかりません。
実行結果
Input a word: zoo
The words zoo is found.
Input a word: daf
The words daf is not found.
Input a word: The words daf is not found.
Input a word: The words daf is not found.
Input a word: The words daf is not found.
Input a word: The words daf is not found.
Input a word: The words daf is not found.
・
・
・
・
このまま最後の文がかなり長く続いて元のコマンド入力待ちの状態にもどります。なぜ最後の行が何十行も続くのでしょうか、fgetsでNを100に定義しているのと関係ありそうな気はしているのですが何を直せばいいのかわかりません。
c
1#include<stdio.h> 2#include<stdlib.h> 3#include<string.h> 4#define N 100 5 6int main(){ 7 int i; 8 char input[N],buf[N],*in,*bu,c; 9 FILE *fp; 10 11//printf("%s\n",input); 12 if((fp=fopen("words","r"))==NULL){//読み込んだ値をfpに代入 13 exit(1); 14 } 15//文字列を一つずつコピーしていき、比較する 16i=0; 17 while(1){ 18 fgets(buf,N,fp); 19 strtok(buf,"\n"); 20 if(buf[i]==EOF)break; 21 bu=buf; 22 //printf("%s\n",bu); 23 24 printf("Input a word: "); 25 fgets(input,N,stdin); 26 strtok(input,"\n"); 27 in=input; 28 29 if(strcmp(in,bu)==0){ 30 printf("The words %s is found.\n",input); 31 } 32 else{ 33 printf("The words %s is not found.\n",input); 34 } 35 i++; 36 } 37 fclose(fp); 38 return 0; 39}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/20 12:29
2018/10/20 12:58