C 程序使用 strtok 在字符串中查找单个单词

标签 c strtok

我正在编写一个程序,我在其中使用 strtok 来查找我在命令行中键入的字符串中的每个单词,在我的示例中,我的代码称为 command.c,因此当我键入时:

./command.out "Hi, there" 

我的结果应该是:

Arg = "Hi, there"
Next word "Hi,"
Next word "there"

到目前为止我的代码将完成打印语句的arg部分,但不会使用execute后面的部分来分隔有问题的字符串,我的代码目前如下:

#include <stdio.h>
#include <string.h>

void main (int argc, char *argv[]) {
  int i;

  for(i =1;i< argc; i++)
    printf("Arg = %s\n", argv[i]);
    char delims[] = " ";
    char *word = NULL;
    word = strtok(argv[i], delims);

    while(word != NULL) {
      printf("Next word \"%s\"\n", word);
      word = strtok(NULL, delims);
    }
}

我哪里出错了,我该如何修复这段代码?感谢大家的帮助

最佳答案

您缺少 for block 周围的大括号:

for(i =1;i< argc; i++)
{
   printf /* ... and so forth */
}

关于C 程序使用 strtok 在字符串中查找单个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16659288/

相关文章:

c - 从字符串中提取子字符串时出现意外行为

C - mystrtok() 函数有什么问题?

c - 为什么用 C 语言打印时会出现这个空行?

java - 发生不可恢复的堆栈溢出

c - 在 C 中获取编译时表达式的值

c - 如果我不包含标题,为什么在调用函数之前清除 EAX?

c - 不理解 strtok() 的结果

c - strtok 中的可变长度

c - 在 C 中获取日期和时间时遇到问题。我寻找答案并尝试了很多,但没有成功,

c - 写入和打印两个字符串交替组合时出现段错误?