【问题标题】:count the number of characters in C计算C中的字符数
【发布时间】:2019-08-11 07:10:11
【问题描述】:

我只需要计算我的“f”文件中的字符数。当我计算一个字符串中的多个字符时,我得到了它的实数,但是当我在我的 .txt 中按“输入”并创建一个新行时,我丢失了 2 个字符。所以,有 4 个字符串和 15 个字符,我的程序告诉我文件中只有 9 个字符。请帮我算一下这个不幸的字符...
这是C语言的代码:

while (!feof(f)) {
    bool space = 1; //remembering last char (was it space or not)
    for (int i = 0; i < len; ++i) { //running till the end of string
        if (a[i] == ' ') {space = 1;} 
        else if (a[i] != '\0' && a[i] != '\n') {
            chars++;
            if (space == 1) {
                words++; //and counting the words
                space = 0;
            }
        }
    }
}

【问题讨论】:

标签: c file count char numbers


【解决方案1】:

在我看来,以下就足够了:

int c; 
while ((c=fgetc(f))!=EOF) {
    if (c == ' ' || c=='\n') {
         words++;
    } 
    else {
        chars++;
    }
}

【讨论】:

  • while (c=fgetc(f)) 不会在 EOF 处停止。不应该是while ((c=fgetc(f))!=EOF)吗?
  • 当然,这并不意味着,如果你计算空格字符,你就有新词。您应该看到,如果最后一个字符是空格,而当前不是。然后你就会有真实的字数;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 2023-02-04
  • 2021-03-25
  • 2011-04-21
相关资源
最近更新 更多