我的程序應該測試迴文,然後將其反向打印出來,但沒有像'!','或'?'這樣的字符。因此,輸入的「夫人我是亞當」輸入「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