c++ - 从用户输入中读取句子并调用递归函数以确定字符串中的字母是否形成回文的程序
问题描述
我们要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.
解决方案
您的代码中没有任何内容分配str
值。您将一个空字符串传递给isPalindrome()
. 因此,您正在访问str[leng - 1]
when str
is empty and leng
is 0
,这很可能是您遇到的错误。
考虑使用以下代码将用户输入的整行、空格和所有内容(直到他们按下Enter键之前)读入str
变量。
getline(cin, str);
推荐阅读
- python - 如何在 PubChemPy 中使用 searchtype 选项
- javascript - 在 express 中通过中间件传递参数
- android - 如何在从服务运行的活动中显示片段?
- java - 从 Eclipse 中的默认包中引用外部文件的问题
- assembly - 如何在 32 位 arm 处理器中加载 64 位数字?
- python - 是否可以根据前一行过滤 Python 中的输出
- ios - 添加到自定义 UICollectionViewCell 时出现意外的 CAShapeLayer 行为
- android - 使用私有源代码发布 android 库(免费)
- c++ - 文件处理 - 值被添加两次而不是一次
- css - 如何在顺风 CSS 中使用 calc()?