编写原型函数(c++)
Writing a prototype function(c++)
我必须编写一个C++函数的原型和实现接收一个字符,如果该字符是元音,则返回true,否则返回false。元音包括以下字符的大写和小写字母"a"e、i、o和u。
我已经写了
bool vowelOrNot(char x)
{ if(x="a" or "e" or "i" or "o" or "u")
cout<<"true"<<endl;
else
cout<<"false""<<endl;
}
我写了,或者因为我不知道怎么写,我的函数正确吗?
正如没有人建议的那样,这里有一个使用switch语句的解决方案:
bool vowelOrNot(char x)
{
switch (x)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return true;
default:
return false;
}
}
我考虑过使用toupper
来转换输入,并且在这种情况下只检查大写字母。
bool vowelOrNot(char x) //x must be lowercase for the function to work as expected
{ if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u' ) //== for comparing and single quotes for a char.
//|| is the logical OR
{
cout<<"true"<<endl;
return true; //return true to function caller
}
else
cout<<"false"<<endl;
return false;//return false to function caller
}
您将需要一个测试,例如
int
main ( int argc, char *argv[] )
{
bool test1 = vowelOrNot ( 'a' );
std::cout << test1 << " expected to be true" << std::endl;
return test1 == true ? EXIT_SUCCESS : EXIT_FAILURE;
}
当然,测试还没有完成。但是您必须为所有可能的输入数据编写测试。
小心使用prototype一词。C++函数原型是一个声明,通常出现在main()之前的文件顶部或模块的头文件中(在您的情况下可能是前者)。它看起来是这样的:
bool vowelOrNot(char);
您所拥有的是实现,但语法不正确。"or"不是C++中的关键字。使用"||"。此外,"=="是等于比较运算符,而不是"="。我建议至少查看以下文件:http://www.cplusplus.com/doc/tutorial/control/.
此外,我注意到你的函数返回了一个布尔值,但你为每个布尔值打印单词,而不是返回它。如果你需要打印这些单词,应该根据函数的返回值在其他地方处理。
我建议的解决方案如下:
#include <string>
#include <cctype>
using namespace std;
bool vowelOrNot(char);
const string VOWELS = "aeiou";
int main
{
//some code that uses vowelOrNot, perhaps printing true and false
}
bool vowelOrNot(char c)
{
return VOWELS.find(tolower(c)) != string::npos;
}
最后,我建议将函数重命名为is_vowel()或类似的名称,以便更清楚、简洁地说明函数的用途。
希望这能有所帮助!
试试这个:
bool vowelOrNot(char x)
{ if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u' || x=='A' || x=='E' || x=='I' || x=='O' || x=='U')
{
cout<<"true"<<endl;
return true;
}
else
{
cout<<"false"<<endl;
return false;
}
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗