C++ 如何初始化长度递归函数

C++ 如何初始化长度递归函数,c++,function,recursion,C++,Function,Recursion,我需要使用上面的函数并在下面的程序中调用,我不确定如何正确初始化它。下面是我尝试过的,但它不起作用。我不允许使用.length(),因为否则程序就会完成 int countChars(string str) { int count = 0; if (str == "") return count; else { count++;// add a character to the count return count

我需要使用上面的函数并在下面的程序中调用,我不确定如何正确初始化它。下面是我尝试过的,但它不起作用。我不允许使用
.length()
,因为否则程序就会完成

int countChars(string str)
{
    int count = 0;
    if (str == "")
        return count;
    else
    {
        count++;// add a character to the count
        return count + countChars(str.substr(1));// function calls itself
    }
}
intmain()
{
char find='\0';
字符串str;
整数计数=0;
int长度=int(countChars);
//请用户输入一个句子

cout函数似乎应该计算字符串中字母的出现次数。如果是这样,则声明和定义不正确。它必须至少有两个参数:类型为
std::string
的对象和类型为
char
的对象

下面展示了这样一个递归函数的外观

int main()
{
    char find = '\0';
    string str;
    int count = 0;
    int length = int(countChars);

    //ask the user for a sentence 
    cout << "Enter a sentence " << endl;
    getline(cin, str);
    //ask the user which letter they want the count of 
    cout << "Which letter would you like to find the number of appearances: " << endl;
    cin >> find;


    for (int i = 0; i < length; i++)
    {
        if (str[i] == find)
        {
            count++;
        }
    }

    cout << "the letter " << find << " appears " << length << " times " << endl;

    //waits for user to exit
    system("pause");
    cin.get();
}
如果你指的是一个只计算字符串长度的函数,那么它可以是

#include <iostream>
#include <string>

size_t countChars( const std::string &s, char c )
{
    return s.empty() ? 0 : ( s[0] == c ) + countChars( { s, 1 }, c );
}

int main() 
{
    std::cout << "Enter a sentence ";

    std::string s;

    std::getline( std::cin, s );

    std::cout << "Which letter would you like to find the number of appearances: ";

    char c = '\0';

    std::cin >> c;


    std::cout << "The letter " << c 
              << " appears " << countChars( s, c ) 
              << " times " << std::endl;

    return 0;
}
Enter a sentence My name is Alycia
Which letter would you like to find the number of appearances: a
The letter a appears 2 times 
并应在声明之后调用

size_t countChars( const std::string &s )
{
    return s.empty() ? 0 : 1 + countChars( { s, 1 } );
}

我想你知道这一点,但是,这是最愚蠢的竞争的一个恰当的例子。我根据愚蠢程度给出了一个接近的投票。@Alycia完全不清楚你想用这个函数做什么。
int length=int(countChars);
what?你在(imho)中初始化
length
最有趣的方式是,你从用户的一些字符串中读取,假装 LangHuth/Cuth>是字符串的长度,最后你假装它是字母的出现的NUBER,而不把它设置成有意义的值。这是一个真正的多用途变量。OP显然是新的C++,甚至是一般的编程,而且它是发布这样一个复杂的解决方案不是很有帮助。你不能在没有注释的情况下使用jst三元运算符和列表初始化,并且期望初学者知道这里发生了什么。
getline(cin, str);