首页 > 解决方案 > 从用户输入中读取句子并调用递归函数以确定字符串中的字母是否形成回文的程序

问题描述

我们要cin.get()在这个程序中使用,但是当我使用它时,它无法确定输入的字符串是否是回文。我什至尝试过,cin.get(str, 0)但这会为我读取一条错误消息。这是我现在拥有的代码。请帮忙。

//program to for palindrome
#include <iostream>
#include <string>
using namespace std;

bool isPalindrome(string str) //will return a true or false value
{
   int leng = str.length(); //local variable for length
   char ch1 = str[0]; //cases if string is 0
   char ch2 = str[leng - 1];//cases if string is not 0
   if(ch1 != ch2) //base case
   {
       return false;
   }
   else
   {
       if(str.length() <= 1)
       {
           return true;
       }
       return isPalindrome(str.substr(1, leng - 2)); //recusive computation
   }
}

int main()
{
   string str; //declare variable str
   cout << "Enter a line that might be a palindrome: "<< endl;
   cin.get();
   bool pal = isPalindrome(str); //assign pal 
   if(pal)
   {
       cout <<"The string is a palindrome." << endl;
   }
   else
   {
       cout <<"The string is NOT a palindrome." << endl;
   }
   return 0;
}

问题是,当它起作用时,它只检查句子中单词的回文,而不是整个句子。我知道解决此问题的方法是忽略或删除空格和非字母字母,但这样做仍然会出错。

这是一个输出样本:

csh> pal
      Enter a line that might be a palindrome:
      Go hang a salami, I'm a lasagna hog.
      The string is a palindrome.

csh> pal
      Enter a line that might be a palindrome:
      This is another candidate string.
      The string is NOT a palindrome.

标签: c++

解决方案


您的代码中没有任何内容分配str值。您将一个空字符串传递给isPalindrome(). 因此,您正在访问str[leng - 1]when stris empty and lengis 0,这很可能是您遇到的错误。

考虑使用以下代码将用户输入的整行、空格和所有内容(直到他们按下Enter键之前)读入str变量。

getline(cin, str);

推荐阅读