char problem

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
iota

char problem

Post 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
Khumba

RE:char problem

Post 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
}
common

RE:char problem

Post 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;
}
Post Reply