计算c编程中文本中的字母和单词数

时间:2013-06-21 09:32:57

标签: c

我尝试编写一个程序来计算从硬盘中存在的文件中取出的文本中的单词和字母。但是这个程序只计算第一行的字母数量。我该怎么办?请提出您对此计划的看法。请在编译器中调试我的代码并帮助我改进它。

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
int letter(const char sentence[ ]);
int words(const char sentence[ ]);
int main(int argc, char *argv[]) {
    char sentence[100];
    const char *filename = "test.txt";
    FILE *cfPtr;
    if (argc == 2)
        filename = argv[1];
    if ( (cfPtr = fopen(filename, "r")) == NULL ) {
        printf( "File '%s' could not be opened\n", filename );
    }
    else {
        int total = 0;
        int total2 =0;
        while (fgets(sentence, sizeof sentence, cfPtr))
            total += words(sentence);
        total2 +=letter(sentence);
        printf("%d\n", total2);
        printf("%d\n", total);
        printf("****%s",*cfPtr);
        fclose(cfPtr);
    }
    getch();
    return 0;
}
int words(const char sentence[ ])
{
    int i, length=0, count=0, last=0;
    length= strlen(sentence);
    for (i=0; i<length; i++)
    {
        if (sentence[i] == ' '||sentence[i] == '\t'||sentence[i] == '\n')
            count++;
    }
    return count;
}
int letter(const char sentence[ ])
{
    int i, length=0, count=0;
    length= strlen(sentence);
    for (i=0; i<length; i++)
    {
        if ((sentence[i]>'a'&&sentence[i]>'z')||(sentence[i]>'A'&&sentence[i]>'Z'))
            count++;
    }
    return count;
}

2 个答案:

答案 0 :(得分:2)

您正在使用while()循环关闭文件。

while (fgets(sentence, sizeof sentence, cfPtr))
    total += words(sentence);
    total2 +=letter(sentence);
    printf("%d\n", total2);
    printf("%d\n", total);
    printf("****%s",*cfPtr);
    fclose(cfPtr); //<------- you want it out of loop
}

答案 1 :(得分:0)

main的更正后的其他部分:

    else {
        int total  = 0;
        int total2 = 0;

        while (fgets(sentence, sizeof sentence, cfPtr)) {
          total  += words(sentence);
          total2 += letter(sentence);   // <<< this must be part of the while loop
        }

        printf("%d\n", total2);
        printf("%d\n", total);
        // printf("****%s",*cfPtr);  <<< this is nonsense and will most likely crash

        fclose(cfPtr);   
    }

考虑letters中的这种情况显然是错误的(我让你自己发现这是一种练习):

(sentence[i] > 'a' && sentence[i] > 'z') || (sentence[i] > 'A' && sentence[i] > 'Z')

BTW:C允许空行和空格,以使源代码更具可读性。