在 c++ 中调用将字符串作为参数传递的函数时出错

Error in calling function passing string as a parameter in c++

本文关键字:参数传递 函数 出错 c++ 调用 字符串      更新时间:2023-10-16

这是我的代码,编译时,当我调用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,并使用字符常量而不是字符串常量进行比较,以便将charchar进行比较。 此外,由于如果条件为真或假,则只需返回 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