递归函数-输出不正确

Recursion functions - Output is incorrect

本文关键字:不正确 输出 递归函数      更新时间:2023-10-16

我正在创建一个程序,该程序使用递归函数来计算句子中的元音,并确定它是否是回文。我遇到的问题是,它说输入的句子不是回文,即使它是。任何帮助都将不胜感激。非常感谢。

#include<iostream> 
#include <cmath>

using namespace std;
struct Sentence
{
    int CountVowels(string , int);
    public:
    Sentence (string);
    bool isPal(string , int);
    void Print();
    string s;
    int numVowel;
    int length;
    //~Sentence();
};
Sentence :: Sentence (string b)
{
    s = b;
    length = 0;
    numVowel = CountVowels(s, 0);
}
int Sentence :: CountVowels(string myWord, int startindex)
{
    length ++;
    int pandi; 
    if(myWord[startindex])
    {
        if (myWord[startindex] != 'a' && myWord[startindex] != 'e' && myWord[startindex] != 'i' && myWord[startindex] != 'o' && myWord[startindex] != 'u')
        {
            pandi = 0;
        }
    else pandi = 1;
    return pandi + CountVowels(myWord, startindex + 1);
    } 
    return 0;
}
bool Sentence :: isPal(string myWord, int size)
{
    int r = myWord.size() - size;
    int t = size - 1;

    if (size == r || r == t)
        return true;

    if ((myWord[r]) != (myWord[t]))
        return false;

    return isPal(myWord, -- size);
}
void Sentence :: Print()
{
    cout << s [-- length];
    if (length == 0)
    {
        cout << endl;
        return;
    }
    Print ();
}
/*Sentence :: ~Sentence()
{
    cout << "ntilde deletenn";
}*/
int main ()
{
    string userW;
    cout << "Enter a sentence: n";
    getline(cin, userW);
    userW.erase(remove_if(userW.begin(), userW.end(), [](char c) {return !isalpha(c); }), userW.end());
    Sentence userSent(userW);
    cout << "The number of vowels in the sentence is " << userSent.numVowel << endl;
    cout << "" << endl;
    cout << "The sentence " << userSent.s << " is" << 
    (userSent.isPal(userSent.s, userSent.s.size()) ? " Palindromen" : " Not Palindromen");

    return 0;
}

更新:我现在正在尝试删除特殊字符。所以它看起来像这个

string userW;
        cout << "Enter a sentence: n";
        getline(cin, userW);
        userW.erase(remove_if(userW.begin(), userW.end(), [](char c) {return !isalpha(c); }), userW.end());

但我得到了这个错误:

In function 'int main()':
88:85: error: 'remove_if' was not declared in this scope

我已经审阅了您的程序。您正在尝试输出函数pint()中的字符串。问题是,当你使用时

 cout << "The sentence backwards is: " << userSent.Print();

但是函数Print()没有任何返回类型。(因为这是无效类型)。这里你应该使用

cout << "The sentence backwards is: " ;
 userSent.Print();

现在它起作用了。

您的代码很好,只是它没有从句子中删除逗号、空格和任何非字母的东西。此外,您还需要对字符进行不区分大小写的比较。这是必需的,否则示例

一个人,一个计划,一条运河,巴拿马

甜点,我强调

不会是栅栏。

要从用户输入中删除特殊字符,可以使用lambda

string userW; cout << "Enter a sentence: n"; getline(cin, userW);
userW.erase(remove_if(userW.begin(), userW.end(), [](char c) {return !isalpha(c); }), userW.end());

EDIT您还可以尝试以下操作来避免对lambda:的需要

  userW.erase(std::copy_if(userW.begin(), userW.end(), userW.begin(), isalpha), userW.end());

要进行不区分大小写的比较,在函数isPal中,您可以更改以下内容:

if((myWord[r])!=(myWord[t])

进入这个:

if (tolower(myWord[r]) != tolower(myWord[t]))