gpt4 book ai didi

c - 纯C如何统计字数、字符数、行数

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:41 26 4
gpt4 key购买 nike

我想统计字数、字符数、换行数,不管我的句子长什么样。 (例如,即使我输入了这样的句子:

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;
}

最佳答案

您不是用纯 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;
}

关于c - 纯C如何统计字数、字符数、行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41195707/

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