c++ - 根据用户输入创建一个字符数组

标签 c++ string char copy palindrome

<分区>

我正在创建一个函数,该函数返回 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;
}
}

最佳答案

可能在您的菜单代码之后。无法重现,因为我没有所需的所有代码,也没有您测试过的输入。

cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

关于c++ - 根据用户输入创建一个字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973779/

相关文章:

c - 返回字符串的函数不工作 - 段错误

c++ - 是否可以在 c/c++ 中将 8 个字符(每个 1 字节)存储在 double 类型(8 字节)的变量中?

android - JSON omdb解析

android - 在android中绘制折线图

error-handling - Pascal : Incompatible types: got “LONGINT” expected “CHAR”

c++ - "friend struct A;"和 "friend A;"语法有什么区别?

c++ - 如何获取_variant_t 的值?

c++ - 在 C++ 中删除韩语字符串中的子字符串

c++ - move 类的构造函数

python - Python中的10个字符组成的字符串集在RAM中的大小比预期的大10倍