slacker wrote:
ok i got the string workin and i even get the string to print but for some reason when i try to compare the string to another, it doesnt match up...
void go_exe(char *command)
{
if(command=="clrscr")
{
clear();
printPROMPT();
};
};
If you think about how the comparison works, and just what you are comparing here, you'll see two reasons this won't work.
In the code you have above, [tt]command[/tt] is a char pointer, whereas "clrscr" is a six element char array constant whose values are
[tt]clrscr[[0]] = 'c'
clrscr[1] = 'l'
clrscr[2] = 's'
clrscr[3] = 'c'
clrscr[4] = 'r'
clrscr[5] = '\00'
[/tt]
You are, in effect, comparing a 4-byte address to the first four elements of the array. Needless to say, this isn't going to work; im surprised the compiler didn't give you an implicit type-cast warning. You need to use the indirection operator, '*', in front of [tt]command[/tt] to get the object it points to rather than the value of the pointer.
However, even if you had used [tt]*command[/tt], it still wouldn't have worked as you wanted it to, because the equality operator ("==") only compares two simple scalar values of the same size; in the case of an array, only the currently indexed variables are compared, with zero (the first item in the array) being the default. So if you have
Code: Select all
char foo[] = "Hello, World!";
char bar[] = "Hello, Sucker!";
Then the test [tt]if (foo == bar)[/tt] returns true, because foo[[0]] and bar[[0]] are both 'H'. Similarly, if you were to call your function with the argument "cat", the expression [tt]if (*command == "clrscr")[/tt] will evaluate to true, since only the first elements of the two strings get compared. To compare two strings, you'd need to loop through them, and compare each element in turn:
Code: Select all
/* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */
#include <string.h>
int
strcmp(const char *s1, const char *s2)
{
while (*s1 == *s2)
{
if (*s1 == 0)
return 0;
s1++;
s2++;
}
return *(unsigned const char *)s1 - *(unsigned const char *)(s2);
}
Fortunately, as Tim pointed out earlier, strcmp() is a standard library function; indeed, this version is taken straight from the DJGPP library code. Hope this clarifies the issue somewhat.
EDIT: Fixed the zero-susbcripted arrays (I forgot that in
BBcode, you need to use "[[[[" and "]]]]" for text outside of a code block.