2

i'm writing a code that read lines of string and check if it's mirrored, palindrome or mirrored palindrome the problem is that it's always displaying wrong value's for inputs except the last one

Sample Input:

NOTAPALINDROME 
ISAPALINILAPASI 
2A3MEAS 
ATOYOTA

Code:

  #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;
}

Output if many strings:

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

Output if one string:

2A3MEAS
^Z
2A3MEAS    0   1
Press any key to continue . . .
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Nader
  • 55
  • 1
  • 6

1 Answers1

2

Your input seems to have additional whitespace that's wrecking your string checks. Evidence of this is that your ouput for the many strings show 5 spaces instead of the 4 it should, except in the final line. Either clean your input manually, or trim your input string in your program. (See, e.g. What's the best way to trim std::string?.)

Community
  • 1
  • 1
Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76
  • I do agree with Aki Suihkonen and unkulunkulu's comments about tweaking your loop, though - your code as it is will fail on even length strings, though that's not the issue you're bringing up. – Scott Mermelstein Mar 12 '13 at 15:42
  • 1
    As an aside, it's very helpful when debugging string issues in any language to have delimiters that help you "see" whitespace. E.g., if your output line was `cout<<'\''<<*pt<<'\''" "< – Scott Mermelstein Mar 12 '13 at 15:48
  • 1
    yes,it's a white space problem and i fixed the loop issue thanks a lot ^_^ – Nader Mar 12 '13 at 15:52