我正在编写一个 shell,我正在使用 getline() 和来自键盘的标准输入来接收命令。不过,我在标记输入时遇到了问题。我尝试在 strtok() 函数中使用\n 作为分隔符,但它似乎不起作用。
例如,我包含了一个 if 语句来检查用户是否键入了“exit”,在这种情况下它将终止程序。它没有终止。
这是我使用的代码:
void main() {
int ShInUse = 1;
char *UserCommand; // This holds the input
int combytes = 100;
UserCommand = (char *) malloc (combytes);
char *tok;
while (ShInUse == 1) {
printf("GASh: "); // print prompt
getline(&UserCommand, &combytes, stdin);
tok = strtok(UserCommand, "\n");
printf("%s\n", tok);
if(tok == "exit") {
ShInUse = 0;
printf("Exiting.\n");
exit(0);
}
}
最佳答案
if (tok == "exit")
tok
和 exit
是指针,因此您正在比较两个指针。这会导致未定义的行为,因为它们不属于同一个聚合。
这不是比较字符串的方式。而是使用 strcmp
。
if (strcmp (tok, "exit") == 0)
关于c - 如何在 C 中解析带有换行符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15115522/