如何初始化递归函数的长度

时间:2017-02-08 22:31:07

标签: c++ function recursion

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

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

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

1 个答案:

答案 0 :(得分:-1)

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

这里显示了这样一个递归函数的外观

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

并应在声明

之后调用
getline(cin, str);