c - 如何在 C 中解析带有换行符的字符串?

标签 c token tokenize strtok

我正在编写一个 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")

tokexit 是指针,因此您正在比较两个指针。这会导致未定义的行为,因为它们不属于同一个聚合。

这不是比较字符串的方式。而是使用 strcmp

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

关于c - 如何在 C 中解析带有换行符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15115522/

相关文章:

c - c 中的文件处理和标记化

PHP 7 OAuthProvider VS random_bytes token 生成

python - 修改 python nltk.word_tokenize 以排除 "#"作为分隔符

c - 猜数字游戏,每个 # 都低

c - 在 Unix 环境中,有没有办法以编程方式在 C 中调用 Which?

c - 尽管管道关闭,读取仍继续阻塞

c++ - 函数返回指向函数指针的指针

ruby-on-rails - 领英 : Exchange JSAPI token to REST's OAuth token

java - 使用斯坦福 coreNLP 进行中文句子分割

c - 通过 C 中的 tokenise 函数从 malloc 泄漏内存