Page 1 of 1

char problem

Posted: Sat Apr 03, 2004 12:00 am
by iota
why dose this code output this testestt3#@ when test is typed
char commandch[255];
int commandint;
if( commandch == "test"){
// do crap
}
commandch[commandint] = ch;
                    commandint++;

any help on code correcttion would be garte
thanks in advanced iota

RE:char problem

Posted: Sat Apr 03, 2004 12:00 am
by Khumba
To compare strings in C, you need to do this instead:

#include <string.h>
if (!strcmp(commandch, "test")) {
//if the strings are equal
}

RE:char problem

Posted: Sat Apr 03, 2004 12:00 am
by common
You're trying to compare a string literal, use strcmp or strcasecmp for case insensitivity.  You may also use strncmp to acquire up to the nth character, or strncasecmp to do the same as strncmp, with case insensitivity.

Example implementation of strcmp (if you require it):

int     strcmp(const char *s1, const char *s2)
{
        while (*s1)
        {
                if (*s1++ != *s2)
                        return *(--s1) - *s2;
                s2++;
        }
        return 0;
}