Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

Wordcounting program in C

So I am trying to write a program that counts the number of words in a text file.

main(void){
    int wordcount = 0;
    FILE *infile = fopen("Text.txt", "r");
    wordcount += word_count(infile);
    printf("%d", wordcount);
    return 0;

    }

int word_count()
{
    int wordcount(FILE *infile);
    int count;
    char it;
    while ((it  = fgets(infile)!=EOF))
    {
        if (it =='
')
        {
            count++
        }
    }
    return count;
}

But when I run it, I got these errors:

infile undeclared identifier
fgets too few aruguments for function call

what am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First up, the segment:

int word_count()
{
    int wordcount(FILE *infile);

should be:

int word_count(FILE *infile) {

Secondly, fgets() takes three arguments, the buffer address, maximum size and file handle.

Third, if fgets() gets something, it returns a pointer to the buffer, not a character. If you're wanting to handle characters, you should be looking into fgetc instead.

Fourth, detecting the character is a good way to count lines but wot words. And you'd probably want to detect a final line without a newline on it as another line anyway (depending on your needs).

If you want to count words, you need to detect transitions between words and non-words.

Fifth, you should either move the word counting function to above main or provide a prototype for it above main. As it is now, it's not declared so you don't have type safety.

And, finally, main() should be declared to return an int.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...