Because in C you have to use strcmp
for string comparison.
In C a string is a sequence of characters that ends with the '\0'
-terminating byte, whose value is 0.
The string "exit"
looks like this in memory:
+-----+-----+-----+-----+------+
| 'e' | 'x' | 'i' | 't' | '\0' |
+-----+-----+-----+-----+------+
where 'e' == 101, 'x' == 120, etc.
The values of the characters are determined by the codes of the ASCII Table.
&command != "exit"
is just comparing pointers.
while(strcmp(command, "exit") != 0);
would be correct. strcmp
returns 0 when both strings are equal, a non-zero
value otherwise. See
man strcmp
#include <string.h>
int strcmp(const char *s1, const char *s2);
DESCRIPTION
The strcmp()
function compares the two strings s1
and s2
. It returns an integer less than, equal to, or greater than zero if s1
is
found, respectively, to be less than, to match, or be greater than s2
.
But you've made another error:
scanf("%c", &command);
Here you are reading 1 character only, this command
is not a string.
scanf("%s", command);
would be correct.
The next error would be
char command[4];
This can hold strings with a maximal length of 3 characters, so "exit"
doesn't
fit in the buffer.
Make it
char command[1024];
Then you can store a string with max. length of 1023 bytes.
In general, of want to save a string of length n
, you need a char
array of
at least n+1
dimension.