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

时间:2018-04-17 17:29:12

标签: c++ string character

这是我的代码,在编译时,当我调用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;
}

3 个答案:

答案 0 :(得分:5)

你的功能是期待string,但你传递的是char。虽然字符串可以包含一个字符,但它不是一回事。类型需要匹配。

将函数更改为期望char,并使用字符常量而不是字符串常量进行比较,以便将charchar进行比较。另外,因为如果条件为真或假,您只是返回true或false,只返回比较表达式的结果。

bool isVowel(char a)
{
    return (a == 'a' || a =='e' || a =='i' || a =='o' || a =='u');
}

答案 1 :(得分:3)

尽可能使用库函数:

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 ); } );

live example

答案 2 :(得分:1)

首先,元音可以有大写或小写。

您的功能声明错误

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 != '\0' && 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