-1
#include <iostream>
#include <cstring>
#include <string>
#include <ctype.h>
using namespace std;
//declare methods
void transform(char *, char *);
bool testPalindrome(char *);
int main()
{
//declare c-strings and a boolean variable
char str[80];
char myStr[100];
char defaultValue[] = "0";
bool done = true;
//continously ask a user to enter a string until the user enters 0
while (done)
{
cout << "Enter a string (0 to exit the program): ";
cin.getline(str, 80);
if (strcmp(str,defaultValue) == 0)
{
done = false;
}
else
{
//convert all lowercase letters of user input to uppercase
transform(str, myStr);
//test if user input is the same when read backward and forward
if (testPalindrome(myStr))
{
cout << "It is a palindrome." << endl;
}
else
{
cout << "It is not a palindrome." << endl;
}
}
}
system("pause");
return 0;
}
/*
This method converts all lowercase letters into uppercase letters
as well as removes characters that are not numbers or letters.
The new string will be stored in the C-string testStr
*/
void transform(char * raw, char * testStr)
{
int length = strlen(raw);
int j = 0;
//convert all lowercase letters to uppercase letters if current letter is lowercase
for(int i = 0; i < length; i++)
{
if (islower(raw[i]))
{
raw[i] = toupper(raw[i]);
}
}
//copy user input, remove all characters that are letters or numbers
for (int k = 0; k < length; k++)
{
if ((isalpha(raw[k]) || isdigit(raw[k])))
{
*(testStr + k) = *(raw + k);
}
else if (isspace(raw[k]))
{
const char * current = &raw[k];
remove(current);
}
j++;
}
*(testStr + j) = '\0';
}
/*
This method determines if the user input can be read the same backward or forward.
will take a parameter of a pointer variable, which refers to
memory address of the c-string
*/
bool testPalindrome(char * str)
{
int test = 1;
bool flag = true;
int length = strlen(str) - 1;
int n = length;
for (int i = 0; i <= length && n >= 0; i++, n--)
{
if (toupper(str[i]) == toupper(str[n]))
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
在此程序中,我試圖顯示用戶輸入是否是迴文。我給5串測試:確定用戶輸入是迴文
雷達
太熱起鬨
夫人我是亞當
一個人,一個計劃,一個運河巴拿馬
!文件,筆記,我的異議!快速從不阻止肥胖;我飲食上鱈魚
出於某種原因,我的程序通過了這5種情況中的4種。另外,我測試了非迴文,它似乎工作得很好。下面的圖像示出了5串是用戶輸入的結果:
正如你可以在圖像中看到,該字符串"A man, A plan, A canal-Panama"
給出相反的結果,而另一個串中提供的預期的效果。我的代碼在哪裏造成這種情況?建議和/或建設性的批評會非常有幫助。
你做了什麼來嘗試和調試呢?例如。調試器逐步完成,輸出中間結果等...? –