我的程序应该测试回文,然后将其反向打印出来,但没有像'!','或'?'这样的字符。因此,输入的“夫人我是亚当”输入“madamimadam”,没有大写字母,空格或标点符号。我能够编写这个程序,但你怎么做另一部分去除这些字符/大写?同样对于我的数组,当程序运行时,它会在打印输出时在回文和回文之间输出一组奇数字符。我相信这是因为数组正在填充额外的字符空间,所以我如何解决这个问题呢?如何使用数组删除特定字符的回文?
#include<iostream>
#include<string>
using namespace std;
int main()
{
//Variables and arrays
int const index = 30;
char Phrase[index];
char Reverse[index];
char* Palindrome = Reverse;
int i, j;
cout << "Please enter a sentence to be tested as a palindrome: ";
cin.getline(Phrase, 30);
int length = strlen(Phrase);
bool test = true;
for(i = 0; i != length/2; i++) //Loops from zero to half of the string
{
if(test) // if it is a palindrome so far
{
if(Phrase[i] != Phrase[length-i-1]) //To check if the characters match
{
test = false;
}
}
else
{
break;
}
}
if(test)
{
cout << endl << "Phrase/Word is a Palindrome." << endl << endl;
for(j = strlen(Phrase) - 1; j >= 0; Palindrome++, j--)
{
*Palindrome = Phrase[j];
}
cout << "The phrase and reverse statement is: " << Reverse << endl << endl;
}
else
{
cout << endl << "Phrase/Word is not a Palindrome." << endl << endl;
}
system("Pause");
return 0;
}
您是否已经逐步调试程序以查看真正发生了什么? –
是的,我有,它通过所有的测试正常运行,但我不知道如何摆脱数组输入的额外字符为空。用户应该能够输入一个体面长度的回文,所以我把数组设置为30 –
回文是相同的事情不是吗?特意从不考虑的字符中划分出来。 – imreal