在在C文件计数的话 [英] Counting words in a file in C

查看:187
本文介绍了在在C文件计数的话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写计数在一个文件中的字的数量的函数。词可以通过空格字符的数量分开。可存在于一个文件中的整数,但该方案应当只计算具有至少一个字母字符的话。

I'm writing a function that counts the number of words in a file. Words may be separated by any amount of whitespace characters. There can be integers in a file, but the program should only count words which have at least one alphabetic character.

int word_count(const char *filename)
{
    int ch;
    int state;
    int count = 0;
    FILE *fileHandle;
    if ((fileHandle = fopen(filename, "r")) == NULL){
        return -1;
    }

    state = OUT;
    count = 0;
    while ((ch = fgetc(fileHandle)) != EOF){
        if (isspace(ch))
            state = OUT;
        else if (state == OUT){
            state = IN;
            ++count;
        }
    }

    fclose(fileHandle);

    return count;  

}

我想通了,如何处理空格,但我不知道该怎么不能算不至少有一个字母字符(我知道因而isalpha和ISDIGIT,但我有困难,了解如何使用组合他们在我的情况)。

I figured out how to deal with whitespaces, but I don't know how not to count combinations which don't have at least one alphabetic character (I know about isalpha and isdigit, but I have difficulty in understanding how to use them in my case).

我真的AP preciate你的帮助。

I would really appreciate your help.

推荐答案

您只需更换:

else if (state == OUT){

else if (state == OUT && isalpha(ch)){

所以,你在第一个字符集的状态,并将其视作字。
要知道,你算 last.First 作为一个单词,可以考虑使用(!字符isalnum(CH))而不是(isspace为(CH))

So you set the state to IN at the first character and count it as word. Be aware that you count last.First as a single word, consider using (!isalnum(ch)) instead of (isspace(ch)).

这篇关于在在C文件计数的话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆