0
#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;
}

我的程序在大多数情况下都可以正常工作,但是当我添加额外的空格时,它会将空格计为额外的单词。例如,

你好吗?
计为 10 个单词,但我希望它改为 3 个单词。如何修改我的代码以使其正常工作?

4

2 回答 2

0

我找到了一种计算单词的方法,在它们之间有几个空格,程序只会计算单词而不是几个空格,因为这里的单词是代码:

nbword是字数,c是键入的字符,prvc是先前键入的字符。

#include <stdio.h>

int main()
{
    int nbword = 1;
    char c, prvc = 0;

    while((c = getchar()) != EOF)
    {
        if(c == ' ')
        {
            nbword++;
        }
        if(c == prvc && prvc == ' ')
            nbword-;
        if(c == '\n')
        {
            printf("%d\n", nbword);
            nbword = 1:
        }
        prvc = c;
    }
    return 0:
}
于 2017-09-30T14:33:24.087 回答
-1

这是一种可能的解决方案:

#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;
}

希望这有帮助,祝你好运!

于 2014-10-31T21:51:29.680 回答