user3880587 user3880587 - 3 years ago 120
C Question

Not counting spaces as words in c

#include <stdlib.h>
#include <stdio.h>

int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;

c = 0;
line = 0;
word = 0;

while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
{
line ++;
}
if (ch == ' ' || ch == '\n' || ch =='\'')
{
word ++;
}
}
printf( "%lu %lu %lu\n", c, word, line );
return 0;
}


My program works fine for the most part, but when I add extra spaces, it counts the spaces as extra words. So for example,
How      are       you?
is counted as 10 words, but I want it to count as 3 words instead. How could I modify my code to get it to work?

Answer Source

This is one possible solution:

#include <stdlib.h>
#include <stdio.h>

int main()
{
    unsigned long c;
    unsigned long line;
    unsigned long word;
    char ch;
    char lastch = -1;

    c = 0;
    line = 0;
    word = 0;

    while((ch = getchar()) != EOF)
    {
        c ++;
        if (ch == '\n')
        {
            line ++;
        }
        if (ch == ' ' || ch == '\n' || ch =='\'')
        {
            if (!(lastch == ' ' && ch == ' '))
            {
                word ++;
            }
        }
        lastch = ch;
    }
    printf( "%lu %lu %lu\n", c, word, line );
    return 0;
}

Hope this helped, good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download