[英]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.