在c中的无限循环中扫描字符串时遇到问题

时间:2016-12-23 08:14:22

标签: 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 个答案:

答案 0 :(得分: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