gpt4 book ai didi

计算C中的字符数

转载 作者:行者123 更新时间:2023-11-30 19:02:48 25 4
gpt4 key购买 nike

我只需要计算“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;
}
}
}
}

最佳答案

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

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

关于计算C中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55263334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com