使用递归函数计算字符串中的元音
count vowels in a string with recursion function
我目前正在攻读信息系统学士学位的最后一年,主修编程。我参加了并通过C++编程 1。我现在正在C++编程 2 并且遇到递归函数的问题。我们有一个家庭作业,假设我们编写一个程序来计算用户输入的字符串中的元音数。我有一个类似于我的 C++ 编程 1 类的程序,它使用 for 循环和 if-then 语句工作。我以为转换这个工作程序很容易使用递归函数,我错了。我有代码(不是找人为我做(,我认为我设置正确。只是不确定在函数中将函数调用放在何处。有人能为我指出正确的方向吗?这是我第一次问问题。如果我附错了代码,请告诉我。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int vowelCount(string, int, int&);
int mail()
{
string input;
int len;
//int x;
//int y;
int count;
count = 0;
cout << "Enter a string of characters with no spaces: ";
cin >> input;
len = input.length();
vowelCount(input, len, count);
cout << "There were " << count << " vowels." << endl;
system("pause");
return 0;
}
int vowelCount(string input, int len, int& count)
{
int y;
int x;
y = input.at(len);
if (len == 1)
{
count = count + 1;
return count;
}
else
{
y = input.at(len);
if ((y == 'a') || (y == 'e') || (y == 'i') || (y == 'o') || (y == 'u') || (y == 'A') || (y == 'E') || (y == 'I') || (y == 'O') || (y == 'U'))
{
count = count + 1;
len = len - 1;
}
else
{
len = len - 1;
vowelCount(string input, int len, int& count);
return count;
}
}
}
return 0;
}
为了大致理解,我推荐这个问题的答案。
首先,这段代码不运行:它有语法错误。 在你有一个至少可以运行的程序之前,你不应该寻求逻辑帮助。 不能调用具有整个签名的函数。 FOr 实例,最后一个块应该是一个简单的
return vowelCount(input, len-1)
将计数作为函数的值和参数返回。 删除参数。
现在,为了理解递归...只需几个步骤即可完成此操作:
- 如果字符串为空,则返回 0。
- 否则,请检查当前信件:
2T 如果是元音,则返回 1 + {字符串其余部分计数}
2F 否则,返回 {计数字符串的其余部分}
您的两个递归调用位于大括号中。 你能从这里拿走吗?
我会按以下方式编写函数
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
std::string::size_type vowelCount( const std::string &input, std::string::size_type pos = 0 )
{
const char *vowels = "AEIOU";
return pos >= input.size()
? 0
: ( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
+ vowelCount( input, pos + 1 );
}
int main()
{
std::string s;
std::cin >> s;
std::cout << "There were " << vowelCount( s ) << " vowels." << std::endl;
return 0;
}
例如,如果输入
AaBbCcDdEe
然后输出将是
There were 4 vowels.
我想字符串不包含嵌入的零字符:)否则,您应该替换条件
( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
为
( input[pos] != ' ' && std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
至于你的函数,那么如果编写它在语法上有效,它没有意义,因为例如这个语句
int vowelCount(string input, int len, int& count)
{
int y;
int x;
y = input.at(len);
^^^^^^^^^^^^^^^^^^
因为根据C++标准成员函数at
5 次投掷:如果 pos>= size(( out_of_range。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 递归函数有效,但无法记忆
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么递归函数的最终输出是 5?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 如何将记忆应用于此递归函数?
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- 这个简单的 C++ 递归函数来反转字符串有什么问题?
- 为什么当从递归函数返回字符串到C 中的Main时,我会得到分割错误
- 无法让我的递归函数正确计算字符串中的字母(c ++)
- 如何使用递归函数使用 4 个字符生成 m 长度字符串数组
- 有没有办法将 int 赋入具有递归函数的字符串中,而无需将数字反转两次
- 用于反转字符串的递归函数
- 使用递归函数计算字符串中的元音
- 字符串递归函数中的字符串错误
- 查找返回6的字符串长度的递归函数太高
- 递归函数扫描字符串以添加ASCII
- c++中使用递归函数来反转字符串
- 通过引用递归函数传递字符串或流对象时出现的段错误