2016-12-23 5 views
-1

ファイルからテキストを入力し、最大長の単語を印刷したいが解決できない!cの無限ループの文字列をスキャンするのに問題がある

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    FILE *ptr_file; 
    char buf[1000]; 
    ptr_file =fopen("text.txt","r"); 
    while (fgets(buf,1000, ptr_file)!=NULL) 
     printf("%s",buf); 
    fclose(ptr_file); 
    int MaxLength = 0, i = 0, counter; 
    while(scanf("%s", buf) != -1) 
    { 
    if (strlen(buf) > MaxLength) 
    { 
     MaxLength = strlen(buf); 
     counter = 0; 
    } 
    if (strlen(buf) == MaxLength) 
     counter++; 
    } 
    printf("%d", counter); 
    return 0; 
} 
+1

ファイル(scanf関数( "%sの"、 ''ながら次いで再度開く - > '一方(関数fscanf(ptr_file、 "%sの"、' – BLUEPIXY

答えて

1
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    FILE *ptr_file; 
    char buf[1000]; 
    ptr_file =fopen("text.txt","r"); 
    while (fgets(buf,1000, ptr_file)!=NULL) 
     printf("%s",buf); 
    fclose(ptr_file); 
    int MaxLength = 0, i = 0, counter; 
    ptr_file =fopen("text.txt","r"); 
    while(fscanf(ptr_file, "%s", buf) != -1) 
    { 
     if (strlen(buf) > MaxLength) 
     { 
      MaxLength = strlen(buf); 
      counter = 0; 
     } 
     if (strlen(buf) == MaxLength) 
      counter++; 
    } 
    printf("%d", counter); 
    fclose(ptr_file); 
    return 0; 
} 

テスト

./a.out 
foo 
bar 
baz 
foobaz 
bletch 
2   
関連する問題