我正在编写我的简单 C shell 的退出部分。
int main(int argc, char*argv[]){
while(1){
char input_line[MAX], *tokens[X_MAX];
int i,n; //n is the number of tokens inside the *tokens
.
.
.//gets the input from user and stores into tokens
.
if(n ==1){
char *ex = "exit";
printf("difference: %i\n",strcmp(tokens[0],ex)); //this prints out 10
}
}
}
当它们明显不同时,我会坚持这一点。我想要做的是,当用户输入“exit”(存储在一个字符数组“tokens”中)时,if 语句将其拾取,然后将其与存储在“ex”中的进行比较。
有什么想法吗?
谢谢
最佳答案
很可能您没有修剪从用户那里获得的字符串,它仍然包含换行符 '\n'
。我跳到这个条件是因为 \n
在 ASCII 中是 10。
为了修剪我用这个:
for (p = line + strlen(line) - 1; p >= line && isspace(*p); --p)
;
p[1] = 0;
不确定我从哪里得到它或者它是否是我的。不过可能不是我的。
关于条件比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14676885/