繁体   English   中英

如何用纯C计算单词,字符和行数

[英]How to count the number of words, characters and lines with pure C

无论我的句子看起来如何,我都想计算单词,字符,换行符的数量。 (例如,即使我输入了这样的句子:

y yafa \\n \\n youasf\\n sd

该程序仍应能够正确计算单词,行,字符的数量)。 我不知道如何用纯C实现这样的程序,有人可以帮我吗?

这是我当前的代码,并且仅在某些条件下才是正确的...

int main() {
    int cCount = 0, wCount = 0, lCount = 0;

    printf("Please enter the sentence you want\n");

    char str[20];
    int j7 = 0;

    while (int(str[j7]) != 4) {
        str[j7] = getchar();
        if (str[0] == ' ') {
            printf("Sentence starts from a word not blank\n");
            break;
        }
        if (int(str[j7]) == 4)
            break;
        j7++;
    }
    int count = 0;
    while (count < 20) {
        if (str[count] != ' ' && str[count] != '\n') {
            cCount++;
        } else
        if (str[count] == ' ') {
            wCount++;
        } else
        if (str[count] == '\n') {
            lCount++;
        }
        count++;
    }

    printf("Characters: %d\nWords: %d\nLines: %d\n\n",
           cCount, wCount++, lCount + 1);
    int x = 0;
    std::cin >> x;
}

您不是用Pure C编写的,而是用C ++编写的。

为了实现您的目标,必须将问题概括为一系列逻辑步骤:

  • 对于每个字符读取:
    • 如果前一个是行分隔符,则换行;
    • 如果前一个是单词分隔符,而当前不是,则您有一个新单词;
    • 如果所有情况下,您都有一个新字符,请将其另存为下一个迭代的前一个字符。

使用'\\n'作为last字符的初始值,因此,如果读取的第一个字符以新行开头,则可能以新单词开头(如果不是空白的话)。

这是一个简单的实现:

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

int main(void) {
    long chars = 0, words = 0, lines = 0;

    printf("Enter the text:\n");

    for (int c, last = '\n'; (c = getchar()) != EOF; last = c) {
        chars++;
        if (last == '\n')
            lines++;
        if (isspace(last) && !isspace(c))
            words++;
    }
    printf("Characters: %ld\n"
           "Words: %ld\n"
           "Lines: %ld\n\n", chars, words, lines);
    return 0;
}

如果需要使用while循环,则可以通过以下方式转换for循环:

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

int main(void) {
    long chars = 0, words = 0, lines = 0;
    int c, last = '\n';

    printf("Enter the text:\n");

    while ((c = getchar()) != EOF) {
        chars++;
        if (last == '\n')
            lines++;
        if (isspace(last) && !isspace(c))
            words++;
        last = c;
    }
    printf("Characters: %ld\n"
           "Words: %ld\n"
           "Lines: %ld\n\n", chars, words, lines);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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