在 c++ 中调用将字符串作为参数传递的函数时出错
Error in calling function passing string as a parameter in c++
这是我的代码,编译时,当我调用isVowel((函数时,它显示类型转换错误。你能检查并告诉错误是什么吗?
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
bool isVowel(string a)
{
if(a == "a" || a =="e" || a =="i" || a =="o" ||a =="u"){
return true;
}
else
return false;
}
int main()
{
int T;
cin>>T;
for (int i = 0; i < T; i++)
{
string s, snew="";
cin>>s;
for (int j=0;j<s.length();j++)
{
if(isVowel(s[j]))
continue;
else
snew += s[j];
}
}
return 0;
}
您的函数期待一个string
但您正在传递一个char
。 虽然字符串可以容纳单个字符,但它不是一回事。 类型需要匹配。
将函数更改为预期char
,并使用字符常量而不是字符串常量进行比较,以便将char
与char
进行比较。 此外,由于如果条件为真或假,则只需返回 true 或 false,因此只需返回比较表达式的结果。
bool isVowel(char a)
{
return (a == 'a' || a =='e' || a =='i' || a =='o' || a =='u');
}
尽可能使用库函数:
bool isVowel( char a )
{
return std::string( "aeiouy" ).find( a ) != std::string::npos;
}
std::copy_if( source.begin(), source.end(), std::back_inserter( target ),
[]( char c ) { return not isVowel( c ); } );
现场示例
对于初学者来说,元音可以有大写或小写。
您的函数声明错误
bool isVowel(string a);
该函数应检查提供的字符是否为元音。
可以按演示程序中显示的方式定义函数。
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <functional>
#include <cstring>
#include <cctype>
bool isVowel( char c )
{
const char *vowels = "aeiou";
return c != ' ' && std::strchr( vowels, std::tolower( ( unsigned char )c ) );
}
int main()
{
std::string s( "Hello Saurav Bhagat" );
std::string new_s;
std::copy_if( s.begin(), s.end(), std::back_inserter( new_s ),
std::not1( std::function<bool( char )>( isVowel ) ) );
std::cout << s << std::endl;
std::cout << new_s << std::endl;
return 0;
}
它的输出是
Hello Saurav Bhagat
Hll Srv Bhgt
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 如何传递带有通过引用传递的结构参数的函数?
- 如何在 c++ 中将函数作为参数传递?
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 将函数作为参数传递以避免重复代码
- 如何在类(C )中作为参数传递函数