C遇到一个小问题。限制自己使用简单的C(即操作系统指令),两个字符串似乎不一样。这是我的代码:
char inputData[256];
int rid;
rid = read(0,inputData,256);
// Strip input
char command[rid];
int i;
for (i = 0; i<=rid-2; i++) {
command[i] = inputData[i];
}
command[rid-1] = '\0';
if (command == "exit") {
write(1,"exit",sizeof("exit"));
}
现在,如果用户在查询时进入“退出”并点击进入,则检测到“退出”的if永远不会运行。有什么想法吗?
谢谢,
编辑:我在去的时候提交git,所以可以在github.com/samheather/octo-os找到当前版本。这显然不是完整的代码,但它证明了问题。
答案 0 :(得分:6)
您无法将字符串与==进行比较。你需要使用strcmp。
if (strcmp(command, "exit") == 0) {
C字符串实际上是字符数组。您可以将“command”视为指向第一个字符的指针。您想要比较字符串中的每个字符,而不仅仅是第一个字符的位置。
答案 1 :(得分:2)
您应该使用strcmp
来比较C中的字符串。
if(strcmp(command, "exit") == 0) //strcmp returns 0 if strings are equal
引用:
A zero value indicates that both strings are equal. A value greater than zero indicates
that the first character that does not match has a greater value in str1 than in str2.
a value less than zero indicates the opposite.
答案 2 :(得分:2)
就目前而言,您将command
的地址与字符串文字"exit"
的地址进行比较,这几乎不可能相同。
您希望将内容与strcmp
进行比较,或者(如果“只有OS指令”表示没有标准库函数)是您自己编写的等效字符串,它遍历字符串并比较它们包含的字符。
答案 3 :(得分:1)
使用标准库中的strcmp
。
答案 4 :(得分:1)
正如其他人所说,==
不适用于字符串。原因是它会比较给出的指针。
在表达式
中command == "exit"
command
是指向数组变量的指针,而"exit"
是指向该字符串的指针,该字符串驻留在只读数据空间中。它们永远不会相同,所以比较总是错误的。
这就是为什么strcmp()
是可行的原因。