如何计算输入流中的单词和行?

时间:2012-09-26 17:20:07

标签: c stream counting

我是C编程新手,我目前正在尝试自学如何创建一个可以计算输入流中的单词和行的C程序,并将两个总计打印到标准输出。

我要做的是让程序计算行数并计算输入流中的单词数。我希望程序包含单词,但要排除空格,制表符,换行符,连字符或冒号。让程序输出结果(单词和行)为小数。

#include<stdio.h>

int main()
{
int iochar;
int words;
int lines;

printf("Enter something here:\n\n");

while ((iochar = getchar ()) !=EOF)
    {
    if((iochar == ' ') || (iochar == '\t') || (iochar == '\n'))

    putchar(iochar);
    }

return 0;
}

我想让程序输出十进制的单词和行数在标准输出中计算。这对我来说似乎没有用。

4 个答案:

答案 0 :(得分:1)

当读取值为lines时,您必须增加\n的值。要计算单词数,您可以看到这些solutions

您也可以使用wc程序(UNIX)...

答案 1 :(得分:1)

尝试使用switch语句而不是if,并添加一些计数逻辑:

int wordLen = 0;
while (...) {
    switch(iochar) {
    case '\n':
        lines++; // no "break" here is intentional
    case '\t':
    case ' ':
        words += (wordLen != 0);
        wordLen = 0;
        break;
    default:
        wordLen++;
        break;
    }
}
if (wordLen) words++;

有一个K&amp; R章节详细介绍了本练习,请参阅 1.5.4字数统计部分。

答案 2 :(得分:0)

您需要阅读标准库函数isspaceispunct;这比对各种字符值进行显式测试更容易(并且需要考虑区域设置)。

您需要将wordslines初始化为0,然后在检查输入时更新它们:

if (isspace(iochar) || ispunct(iochar) || iochar == EOF)
{
  if (previous_character_was_not_space_or_punctuation)  // you'll have to figure
  {                                                     // out how to keep track 
    words++;                                            // of that on your own
  }

  if (iochar == '\n')
  {
    lines++;
  }
}

答案 3 :(得分:0)

如AK4749所述,您没有任何计数代码。

同样在if语句中,如果是空格,制表符或换行符,则只输出字符到stdout。我相信你想要相反。

我会尝试以下内容:

#include "stdio.h"

int main()
{
    int iochar, words,lines;
    words=0;
    lines=0;


    printf("Enter something here:\n\n");

    while ((iochar = getchar ()) !=EOF)
    {
        if((iochar == ' ') || (iochar=='\t')) 
            words++;
        else if (iochar == '\n')
            lines++;
        else
        {
            putchar(iochar);
        }
    }
    printf("Lines: %d, Words: %d", lines, words);
    return 0;
}

我没有尝试编译它,但它不应该太远。

希望它有所帮助, Lefteris