首页 文章

如何用C中的换行符解析字符串?

提问于
浏览
1

我正在写一个shell,我正在使用getline()和键盘中的stdin来接受命令 . 我虽然难以对输入进行标记 . 我尝试在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);
   }
}

2 回答

  • 0

    正如@Kirilenko所说,你不能使用==运算符来比较字符串 .

    但是's not it. If you'重新使用getline()你在循环中调用strtok()直到它返回NULL .

  • 3
    if (tok == "exit")
    

    tokexit 是指针,所以你要比较两个指针 . 这会导致未定义的行为,因为它们不属于同一个聚合 .

    这不是比较字符串的方法 . 请使用 strcmp .

    if (strcmp (tok, "exit") == 0)
    

相关问题