如何在单词中打印元音

How to print vowels in a word?

本文关键字:打印 单词中      更新时间:2023-10-16

不使用数组、向量或函数!从每个人的教科书c_for解决这个问题。

问题 - 编写一个程序来读取单词并打印单词中的元音数。在本练习中,假设 a e i o u y 是元音。例如,如果用户提供输入"Harry",程序将打印 2 个元音

尝试-

#include <iostream>
#include <cstring>

using namespace std;
int main()
{
cout <<"Please enter a word" ;
char alpha;
cin>> alpha; 
int count = 0;

for ( int i=0; i <= alpha.length(); i++)
{
if (alpha == 65 || alpha == 69 || alpha == 73 || alpha == 79 || alpha == 85 || alpha == 89)
    count++;
}
cout << count << " vowels." ;

return 0;

显示此错误且无法编译 - p.4.13.cpp:15:27:错误:成员引用基类型"char"不是结构或联合。感谢您的帮助!

尝试使用 std::string(或字符数组,char[])代替 char,"char" 是基元类型,它不是结构体,也没有可以通过 "." 运算符访问的成员。

有更好的方法可以做到这一点,但只是尝试发布一些接近你原来的东西,我可以做到。

#include <iostream>
#include <string>

using namespace std;
const string vowels{ "aeiouy" };
int main()
{
    cout << "Please enter a word: ";
    std::string alpha;
    getline( cin, alpha, 'n' );
    int count = 0;
    for( const auto& letter : alpha ) {
        if( string::npos != vowels.find( letter ) ) ++count;
    }
    cout << count << " vowels.";
    cout << 'n' << 'n';
    system( "PAUSE" );
    return 0;
}