我正在创建一个函数,该函数返回true或false,表示单词是否为回文结构,也忽略了字符串中的空格。
例如,“taco cat”将被视为回文。
我正在接受通过getline检查的字符串,但是wordA.length总是返回0,我不知道该修复什么。
任何帮助都将不胜感激。
谢谢!
bool checkPalindrome() {
string wordA;
cout << "The word is: " << endl;
getline(cin, wordA);
cin.clear();
cin.ignore(10000, '\n');
//This outputs 0
cout << wordA.size() << endl;
char* wordB = new char[wordA.length()+1];
int j = 0;
for (unsigned int i = wordA.length() - 1; i > 0; i--) {
wordB[j] = wordA[i];
j++;
}
int k = 0;
for (unsigned int i = 0; i < wordA.length(); i++) {
if (wordA[i] == ' ') {
continue;
}
while (wordB[k] == ' ') {
k++;
}
if (wordA[i] != wordB[k]) {
cout << "It's not a palindrome" << endl;
delete[] wordB;
return false;
}
k++;
}
cout << "It is a palindrome" << endl;
delete[] wordB;
return true;
}
int main()
{
int response;
cout << "Enter test case " << endl << endl;
cout << "0: Sort" << endl;
cout << "1: Get Permutations" << endl;
cout << "2: Check Permutations" << endl;
cout << "3: Check Permutation Palindrome" << endl << endl;
cout << "Selection: ";
cin >> response;
switch (response) {
case 0:
mergeCase();
break;
case 1:
permutationCase();
break;
case 2:
checkPermutation();
break;
case 3:
checkPalindrome();
break;
}
}
答案 0 :(得分:0)
可能是您的菜单代码之后。无法复制,因为我没有所需的所有代码,也没有您测试过的输入。
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');