[英]Segmentation fault (core dumped) recursive function
I am getting a segmentation fault (core dump) for this recursive function to count vowels within a string which is inputted by the user.我遇到了这个递归函数的分段错误(核心转储),以计算用户输入的字符串中的元音。 My objective is to copy the user inputted string variable into a character array then lowercase and verify whether or not the character is a vowel.
我的目标是将用户输入的字符串变量复制到字符数组中,然后小写并验证该字符是否为元音。 After verification, the function should execute the recursive addition of the vowel count.
验证后,该函数应执行元音计数的递归加法。 I am passing an integer of 0 as the parameter int L in this function.
我在这个函数中传递一个整数 0 作为参数 int L 。 Any info on what I can do to fix and improve this portion of code would be awesome.
关于我可以做些什么来修复和改进这部分代码的任何信息都会很棒。
#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
using namespace std;
int vowels(string s, int L)
{
int sum = 0;
char str[s.length()-1];
strcpy(str,s.c_str());
if(str[L])
{
tolower(str[L]);
if(str[L]!='a'||str[L]!='e'||str[L]!='i'||str[L]!='o'||str[L]!='u')
sum = 0;
else
sum = 1;
return sum += vowels(s,L++);
}
else
return 0;
}
There are several problems with your code:您的代码有几个问题:
[]
operator on string.[]
运算符。 Why segmentation fault happens?为什么会发生分段错误?
strcpy
copies a string until null-char is reached. strcpy
复制一个字符串,直到达到空字符为止。 So you need a char array of s.length()+1
elements not s.length()-1
, if not segmentation fault happens.所以你需要一个
s.length()+1
元素而不是s.length()-1
的字符数组,如果不是分段错误发生。
Noting those points, here is a modified code:注意到这些要点,这里是一个修改后的代码:
int vowels(string::const_iterator beg, string::const_iterator end) {
int sum = 0;
if (beg != end) {
switch (*beg) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return 1 + vowels(++beg, end);
}
return vowels(++beg, end);
}
return 0;
}
Working code:工作代码:
#include <string>
#include <iostream>
using namespace std;
int vowels(string::const_iterator beg, string::const_iterator end) {
int sum = 0;
if (beg != end) {
switch (*beg) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return 1 + vowels(++beg, end);
}
return vowels(++beg, end);
}
return 0;
}
int main() {
string x = "hello canberk";
cout << vowels(x.begin(), x.end()) << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.