计算每个单词的元音

时间:2018-10-07 08:52:07

标签: c++

在给定的文本中,我必须数一数传达单词的元音。我的尝试:

#include <iostream>
#include <string.h>

using namespace std;

char s[255], *p, x[50][30];
int c;

int main()
{
    cin.get(s, 255);
    cin.get();
    p = strtok(s, "?.,;");
    int n = 0;
    while (p)
    {
        n++;
        strcpy(x[n], p);
        p = strtok(NULL, "?.,;");
    }
    for (int i = 1; i <= n; i++)
    {
        c = 0;
        for (int j = 0; j < strlen(x[i]); j++)
            if (strchr("aeiouAEIOU", x[i][j]))
                c++;
        cout << c << " ";
    }
    return 0;
}

PS:我知道我的代码是C和C ++的混合体,但这就是我在学校所教的。

2 个答案:

答案 0 :(得分:0)

这是我的解决方案:

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    char s[255];
    int n,i,counter=0;
    cin.get(s,255);
    for(i=0; i<=strlen(s)-1; i++)

        if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u') counter++;

     cout<<counter;
    return 0;
}

如果您有一个元音(a,e,i,o或u),那么您将累加到计数器上。 您也可以使用strchr,但这是一种更简单易懂的方法。

答案 1 :(得分:0)

案例已在评论中关闭。

但是,为了好玩,我建议您使用另一种变体,该变体避免使用可怕的strtok(),不需要冒险的strcpy(),并且仅处理每个输入字符。

由于您受制于老师的混合风格,并且显然还不应该使用c ++字符串,因此我也尊重此约束:

const char separators[]=" \t?.,;:"; // I could put them in the code directly
const char vowels[]="aeiouyAEIOUY"; //    but it's for easy maintenance
int vowel_count=0, word_count=0;
bool new_word=true; 
char *p=s;
cout << "Vowels in each word: ";
do  {
    if (*p=='\0' || strchr(separators,*p)) {
        if (!new_word) {   // here, we've reached the end of a word
            word_count++; 
            cout << vowel_count << " ";
            vowel_count = 0; 
            new_word=true; 
        }                 // else it's still a new word since consecutive separators
    } 
    else {               // here we are processing real chars of a word
        new_word=false;   // we have at least on char in our word
        if (strchr(vowels, *p))
            vowel_count++;
    }
} while (*p++);  // It's a do-while so not to repeat the printing at exit of loop
cout << endl<<"Words: "<<word_count<<endl; 

Demo