c++ - 回文和镜像字符串

标签 c++ visual-c++

我正在编写一个代码来读取字符串行并检查它是否是镜像、回文或镜像回文 问题是,除了最后一个之外,它总是显示错误的输入值

示例输入:

NOTAPALINDROME 
ISAPALINILAPASI 
2A3MEAS 
ATOYOTA

代码:

  #include<iostream>
  #include<string>
  #include<vector>
  using namespace std;

bool is_palindrome(const string &s)
{
    for(int i=0,j=s.length()-1;i!=j;i++,j--)
    {
        if(s[i]!=s[j])
            return false;
    }
    return true;
}
char get_mirror(const char &c)
{
    switch(c)
    {

    case 'A':return c;
    case 'E':return '3';
    case 'H':return c;
    case 'I':return c;
    case 'J':return 'L';
    case'L':return 'J';
    case'M':return c;
    case 'O':return c;
    case 'S':return '2';
    case 'T':return c;
    case'U':return c;
    case'W':return c;
    case'X':return c;
    case'Y':return c;
    case'Z':return '5';
    case'1':return c;
    case'2':return 'S';
    case'3':return 'E';
    case'5':return 'Z';
    case'8':return c;
    default: return'-1'; 

    }
}
 bool is_mirrored(const string &s)
 {
     for(int i=0,j=s.length()-1;i!=j;i++,j--)
     {
         if(get_mirror(s[i])!=s[j])
         {
             return false;

         }
     }
     return true;

 }

int main()
{
    vector<string>cases;
    vector<string>::iterator pt;
    string temp;
    while(getline(cin,temp))
    {
        cases.push_back(temp);

    }
    for(pt=cases.begin();pt!=cases.end();pt++)
    {
        cout<<*pt<<"    "<<is_palindrome(*pt)<<"   "<<is_mirrored(*pt)<<endl;
    }

    system("pause");
    return 0;
}

如果有多个字符串则输出:

NOTAPALINDROME
ISAPALINILAPASI
2A3MEAS
ATOYOTA
^Z
NOTAPALINDROME     0   0
ISAPALINILAPASI     0   0
2A3MEAS     0   0
ATOYOTA    1   1
Press any key to continue . . .

输出一个字符串:

2A3MEAS
^Z
2A3MEAS    0   1
Press any key to continue . . .

最佳答案

您的输入似乎有额外的空格,这会破坏您的字符串检查。证据是,许多字符串的输出显示 5 个空格,而不是应有的 4 个空格,除了最后一行。手动清理输入,或在程序中修剪输入字符串。 (例如,参见What's the best way to trim std::string?。)

关于c++ - 回文和镜像字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15364986/

相关文章:

c++ - 为什么在 C++ 中默认签名为 'char'?

c++ - 使用C++在打印机上打印pdf文件

.net - C++/cli 识别托管/非托管之间的转换并测量其成本

c++ - C++ 流插入运算符的返回类型是否必须是 std::ostream?

c++ - 如何将 C 转换为 C++?

Visual Studio 2010 中的 C++ 片段支持

c++ - 使用以 lambda 作为成员的成员初始值设定项列表时出现 VC++ 2013 错误

C++ MFC 应用程序在 Windows 7 上运行缓慢,但在 XP 上运行迅速

c++ - 是一个函数指针 odr-如果它被调用

c++ - loop() 函数外的无限循环