【发布时间】:2014-01-30 23:26:50
【问题描述】:
因此,对于 C 类的介绍,我们必须编写一个程序来计算文件中的行数、字符数和单词数。在程序中,单词被定义为以字母开头的一系列字母、数字和撇号。出于某种原因,计算单词的逻辑对我不起作用,也许是因为我是 C 新手,或者因为我一直不擅长制定逻辑。我的代码现在,当传入
hey whats up\n
hey what's up\n
hey wh?ts 'p\n
返回 3 行,31 个单词,40 个字符。感谢您的帮助,我知道这是一个超级蹩脚的问题,它只会让我发疯。
这是我的代码:
#include <stdio.h>
typedef enum yesno yesno;
enum yesno {
YES,
NO
};
int main() {
int c; // character
int nl, nw, nc; // number of lines, words, characters
yesno inword; // records if we are in a word or not
yesno badchar;
// initialize variables:
badchar=NO;
inword = NO;
nl = 0;
nw = 0;
nc = 0;`
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c == '\t')
inword = NO;
else if (inword == NO) {
inword = YES;
}
while (inword == YES){
if (( c<'A' || c>'Z')||(c<'a'||c>'z')||(c<'0'|| c>'9') ){
inword= NO;
//badchar = YES;
}
if (( c<'A' || c>'Z')||(c<'a'||c>'z')|| (c<'0'|| c>'9') ||(c!= '\'')){
nw=nw;
inword = NO;
//badchar=YES;
}
if(badchar==NO){
nw++;
badchar=NO;
inword= NO;
}
}
}
printf("%d %d %d\n", nl, nw, nc);
}
【问题讨论】:
-
能否请您修复缩进/格式?您的代码目前很难阅读。
-
我很想,但由于某些原因,在我的电脑上输入代码的方法似乎很笨拙。我基本上只是将代码粘贴进去,然后每行按 [space] 四次。
-
字数问题是每次在一个单词中使用另一个字母时都会增加字数。只需要在从 in a word 变为 out of a word 时增加它。
-
我意识到,出于某种原因,只需将
badchar变量打开到NO就会导致无限循环 -
程序在没有 badchar 代码的情况下可以工作吗?我的意思是任何非空格字符都可以组成一个单词,它是否输出正确数量的单词?如果没有,我会少担心 badchar 的东西,而是首先专注于弄清楚如何计算单词。之后 badchar 代码应该很容易了。