...

View Full Version : C loop, giving me trouble !! Can anyone help..?



rossen
06-11-2008, 01:50 PM
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 <stdio.h>
#include <ctype.h>
#include <string.h>

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;
}
thanks,
-------------------------------------------
Girly Lay outs (http://www.********************) vegetarian diet (http://www.veggie123.com)

Gox
06-11-2008, 10:33 PM
From a quick look at your code my guess is there might be an issue with the value for "i" for subsequent loops.

It looks like your code is doing the following:
i = 0
read char 'a'
s[i] = a
i = 1
read char 'b'
s[i] = b
i = 2
read char '\n'
s[i] = '\0'
"not a palindrome"
-----------
Loop,
read char 'c'
s[i] = c
i = 3
read char '\n'
s[i] = '\0'
etc..
-----

Do you see the issue? When you're reading the first word using my above example S would look like: s[0] = a, s[1] = b, s[2] = \0, and i = 2.
Then when we loop you don't reset i back to 0 so your s[] gets overwritten to the following: s[0] = a, s[1] = b, s[2] = c, s[3] = \0, i = 3.

Try setting i = 0 when you start reading a new word and see if that helps:
while(1){
i = 0;
while{
....

I haven't run your code, so this is merely a guess. But I'd take a look at that and see if it helps.

Gox



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum