Sunday, August 2, 2009

C loop, giving me trouble !! Can anyone help..?

i have this code to test for palindromes, it functions perfectly well on the first test, but as the program continues to check for more after the first word it keeps printing not palindrome, once it wasnt the first word typed, run it pls, and you'll c what im talking about. Can anyone help me fix it..?








#include %26lt;stdio.h%26gt;


#include %26lt;ctype.h%26gt;


#include %26lt;string.h%26gt;





int isPalindrome( char *s);


int main (void)


{


int i=0;


int ch;


char s[100];


while (1){


while ((ch = getchar()) != ('\n')){


if (isalpha(ch)){


ch=toupper(ch);


s[i]=ch;


i++;


}


}


s[i]='\0';


if (isPalindrome(s) ==1){


printf("is palindrome\n");


}


else{


printf("not palindrome\n");


}


system("Pause");


return 0;


}

C loop, giving me trouble !! Can anyone help..?
What you are doing when you pass a char * into a function is essentially passing a pointer to the first char in the array.





This will always start with the first word you enter, and since you are storing all the strings on the same array, there is no way to delineate the different strings.





reseting the i to variable to zero after every call to isPalindrome()
Reply:You need a way to break out of your while(1) loop. Otherwise, you'll just keep asking for chars over and over again.





One way to do this is that if getchar() == \n you can call break;, which will break the outer loop.





A nicer way is to set a flag = true before you enter the main loop, and use while(flag)





then if the character is a carriage return, set flag to false, and the loop rops out naturally.
Reply:You need to initialize your index i in the loop:





while (1){


i = 0;


while ...





You'd be wise to ensure the user doesn't enter more than 100 characters, causing you to overrun your array s[100]. If this is just a toy program for an assignment, it may not matter. Still, it's good to get in the habit of writing robust code.


No comments:

Post a Comment