简体   繁体   中英

Strcmp() doesn't seem to work in my C program?

I am writing a program to check whether a given word is a palindrome(a word spelled the same forwards and backwards.)

It's almost complete, but now I'm having an issue with strcmp(). Even if the forwards word and the reversed word are the same, it never returns a 0.

Here is the function that checks forwards versus backwards. If this isn't enough code, let me know.

bool isPalin(char msg[])
{
    int len = strlen(msg);
    char backwards[400]="";
    char letchar[2]="";
    int i;
    for(i=len-1;i>=0;i--){
        sprintf(letchar,"%c",msg[i]);
        strcat(backwards,letchar);
        strcpy(letchar,"");

    }

    if(strncmp(msg,backwards,(len/2))==0){return true;}
    else {return false;}
}

EDIT: Thank you all for your help, but apparently the problem was totally unexpected. I had a newline in one of my strings but not the other (still not sure why) but I was able to remove the newline and it worked for me. I also made the optimizations you guys recommended. I suck at optimizing :P

Why bother with strcmp anyway?

int i = 0;
while(len > 1)
{
 if(msg[i] != msg[len-i-1]) return false;
 i++;
 len = len - 2;
}

return true;

If you suspect a function isn't working properly, eliminate the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM