因此,對於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);
}
您能否修復縮進/格式化?您的代碼目前很難閱讀。 – Macattack
我想,但由於某些原因,在我的電腦上輸入代碼的方法似乎非常笨拙。我基本上只是粘貼代碼,然後按下[空格]四行每行。 –
單詞計數的問題在於,每次在單詞中使用另一個字母時,都會增加單詞數量。當你從一個詞改變成一個詞時,你只需要增加它。 – Macattack