标准输入 - 计数字符/单词/行

时间:2016-03-13 20:12:24

标签: c

我已经编写了一些代码来查找标准输入中的字符,行和单词的数量,但我有几个问题。

  1. 运行程序时 - 它不会抓取我的任何输入。我可以使用shell重定向吗?

  2. 我的字数 - 仅在getchar()等于escape'或' '空格时计算。我想要它,如果它在ASCII表的十进制值范围之外,它也会计数。 IE浏览器。如果getchar() !=a->zA->Z或',wordcount += 1范围内。

  3. 我在考虑使用十进制值范围来表示范围 - 即:getchar() != (65->90 || 97->122 || \' ) -> wordcount+1

    参考

    https://en.wikipedia.org/wiki/ASCII

    这是解决这个问题的最好方法吗?如果是这样,实施该方法的最佳方法是什么?

    #include <stdio.h>
    
    int main() {
        unsigned long int charcount;
        unsigned long int wordcount;
        unsigned long int linecount;
        int c = getchar();
    
        while (c != EOF) {
            //characters
            charcount += 1;
    
            //words separated by characters outside range of a->z, A->Z and ' characters.
            if  (c == '\'' || c == ' ')
                wordcount += 1; 
    
            //line separated by \n 
            if (c == '\n')
                linecount += 1;
        }    
        printf("%lu %lu %lu\n", charcount, wordcount, linecount);
    }
    

2 个答案:

答案 0 :(得分:2)

您的代码有多个问题:

  • 您不会初始化charcountwordcountlinecount。具有自动存储的未初始化的局部变量必须在使用前初始化,否则您将调用未定义的行为。
  • 您只从标准输入读取一个字节。你应该继续阅读,直到你得到EOF
  • 您检测单词的方法不正确:'是否是分隔符是值得怀疑的,但您似乎想要特别考虑它。标准wc实用程序仅考虑使用空格来分隔单词。此外,多个分隔符应仅计为1。

这是一个带有语义的修正版本,即单词由字母组成,其他所有内容都计为分隔符:

#include <ctype.h>
#include <stdio.h>

int main(void) {
    unsigned long int charcount = 0;
    unsigned long int wordcount = 0;
    unsigned long int linecount = 0;
    int c, lastc = '\n';
    int inseparator = 1;

    while ((c = getchar()) != EOF) {
        charcount += 1;  // characters
        if (isalpha(c)) {
            wordcount += inseparator;
            inseparator = 0;
        } else {
            inseparator = 1;
            if (c == '\n')
                linecount += 1;
        }
        lastc = c;
    }
    if (lastc != '\n')
        linecount += 1;  // count the last line if not terminated with \n

    printf("%lu %lu %lu\n", charcount, wordcount, linecount);
}

答案 1 :(得分:0)

你需要:

while((getchar()) != EOF )

随着你的头脑循环。正如你所拥有的那样,getchar会读取一个字符,而while块会循环而没有进一步的 getchar()开始!