简体   繁体   中英

counting specific words in a string in c

A program that counts words that are alphanum or have _ in them but the first character is not a number.

#include <ctype.h>
#include <stdio.h>
int main() 
{
    int count = 0;
    for (;;) 
    {
        int c = getchar();
        if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95) 
        {
            c = getchar();
            while(isalnum(c) || c == 95) 
            {
                c = getchar();
                continue; 
            }
            if (c == EOF || isspace(c))
                count++;
        }
        while (c != EOF && !isspace(c))
            c = getchar();
        if (c == EOF || c == '\n') 
        {
            printf("%d\n", count);
            count = 0;
            if (c == EOF)
                break;
        }
    }
    return 0;
}

but my problem is that if there is an empty line this should output nothing. I mean for example input is this:

input:

counting _words in* sentence
how many words are here?

In this input the last line is empty: it has no space and nothing. but there is '\n' after the second sentence. the output of my code is:

output:

3
4
0

3 and 4 are correct but I don't want that 0 on the last line. It has to be

3
4

does this make sense? How can I do that?

If the current input character is a newline, and the next input character is also a newline, then ignore that line. Use ungetc to "unread" the next character, if it happens not to be a newline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM