我如何计算单词数?

时间:2019-03-17 04:18:59

标签: c++

我如何使此代码针对计数单词的单词计数运行。每当我放一堆....或!!!!它给了我13个以上的字数,这是不正确的。

当我使用Tab键或“ ....”时,它最终会给我很大的数字,或者不包括它们。单词还包括(,;:!?)组。

string word;
int voweltally(0), contally(0), uppertally(0), lowertally(0), punctally(0), wordtally(1);
int d;

cout << "Enter some text. Letters and the following punctuation only please . , : ; ! ?" << endl;
cout << "Pressing enter/return will end the text." << endl;
getline (cin, word);

d=word.length();


for (int i=0; i<d; i++) {
    if (((toupper(word[i])=='A')||(toupper(word[i])=='E')||(toupper(word[i])=='I')||(toupper(word[i])=='O')||(toupper(word[i])=='U'))) {
        voweltally++;
    }
    else {
        if (((word[i]!='.')&&(word[i]!=',')&&(word[i]!=':')&&(word[i]!=';')&&(word[i]!='!')&&(word[i]!='?'))&&(word[i]!=' ')&&(word[i]!='\t'))
        contally++;
    }
}


for (int i=0; i<d; i++) {

    if (isupper(word[i])){
        uppertally++;
   }
    else if (islower(word[i])) {
        lowertally++;
    }      
}

for (int i=0; i<d; i++) {

    if ((word[i]=='.')||(word[i]==',')||(word[i]==':')||(word[i]==';')||(word[i]=='!')||(word[i]=='?')) { // good
        punctally++;
    }

在计算单词数之前,一切都很好,这是我计算单词数的两个初步想法

    //if (((word[i]!=' ')||(word[i]!='\t'))&&((word[i+1]==' ')||(word[i+1]=='\t'))) { //check work on this
}
for (int i=0; i<d; i++) {
    if (((word[i]!=' ')||(word[i]!='\t'))&&(word[i+1]==' ')){
    wordtally++;
    }
}


cout << "The number of vowels is: " << voweltally << endl;
cout << "The number of consonants is: " << contally << endl;
cout << "The number of uppercase letters is: " << uppertally << endl;
cout << "The number of lowercase letters is: " << lowertally << endl;
cout << "The number of punctuation characters is: " << punctally << endl;
cout << "The number of words is: " << wordtally << endl;
cout << "Exiting program ..." << endl;

return 0;
}

1 个答案:

答案 0 :(得分:0)

如果按以下方式实施,也许可以进行字数统计。

for (int i = 1; i < d; i++) {
  if (isalpha(word[i - 1]) && !isalpha(word[i])) {
    wordtally++;
  }
}
if (d > 0 && isalpha(word[d - 1])) {
    wordtally++;
}