470,864 Members | 1,723 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,864 developers. It's quick & easy.

reading string without spaces and capital letters

I am writng a program that takes a string and it must output if it is a palindrome,
A palindrome is a string that is spelled and read the same way forward and backward, it workes fine with one word but if there is spaces or capital lettersor commas it won't work I used getline but without any effect.here is the code.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main ()
  6. {
  7.     char s[100];
  8.     int i,j;
  9.     bool match=true;
  10.     cin.getline(s,100,'\n');
  11.     cout<<endl;
  12.     i=0;
  13.     j=strlen(s)-1;//because of the \0
  17.     while(match&&(i<j))
  18.     {
  19.         if(s[i]!=s[j])
  20.             match=false;
  21.         i++;
  22.         j--;
  23.     }
  24.     if (match)
  25.         cout<<"It is a palindrome"<<endl;
  26.     else
  27.         cout<<"It is not a palindrome"<<endl;
  29.     return 0;
  30. }
can anyone help? thank you.
Dec 2 '07 #1
2 3763
Never rely to much on C getline if you have to do line-level character computations;use instead a getchar:getchar fetches a byte from the standard input;you should embed it in a while loop
Expand|Select|Wrap|Line Numbers
  1. while (c= getchar() != \n)
  2.  do your computations
is that clear enough?I hope so
have a good sunday!
Dec 2 '07 #2
9,208 Expert Mod 8TB
You need to ignore spaces in the compare inside your loop.

That is, if s[i] is a space you need a loop so skip all spaces until the next character. Ditto for s[j]. Maybe you write a a function to call here. It can take the input sttring and current position as arguments plus a third argument to say whether to go forwards are backwards in the string. It could return the position of the next non-space character, or -1 if you run out of string. Then you can call this function rather than using ++i and ++j in your loop.

BTW, your cin.getline is just fine. getchar() is a C carry over to C++ and is not required in this case.
Dec 2 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by - ions | last post: by
4 posts views Thread by Carlos Marangon | last post: by
6 posts views Thread by Gidi | last post: by
22 posts views Thread by hg | last post: by
12 posts views Thread by aparnakakkar2003 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.