【问题标题】:strtok is using wrong delimiterstrtok 使用了错误的分隔符
【发布时间】:2010-08-10 06:47:14
【问题描述】:

当我将分隔符指定为“,”时,为什么我的strtok 会在空格后拆分我的字符串?

【问题讨论】:

  • 你能举个例子吗?
  • 嗯,是的,猜测问题还为时过早:P
  • 我正在使用 strtok 读取逗号分隔的文本文件并指定“,”作为分隔符,但不是给我“Jeremy Whitfield”它只返回“Jeremy”
  • 说真的,请发布您的实际代码。帖子:(1)您正在使用的实际源代码; (2) 输入文件中的示例行; (3) 你的程序的实际输出; (4) 预期输出。

标签: c delimiter strtok


【解决方案1】:

我只能建议您做错了什么,尽管很难准确判断是什么(在询问具体情况时,您通常应该发布您的代码)。示例程序,如下所示,似乎工作正常:

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

int main (void) {
    char *s;
    char str[] =
        "This is a string,"
        " with both spaces and commas,"
        " for testing.";
    printf ("[%s]\n", str);
    s = strtok (str, ",");
    while (s != NULL) {
        printf ("   [%s]\n", s);
        s = strtok (NULL, ",");
    }
    return 0;
}

它输出:

[This is a string, with both spaces and commas, for testing.]
   [This is a string]
   [ with both spaces and commas]
   [ for testing.]

立即想到的唯一可能是您使用" ," 而不是","。在这种情况下,您会得到:

[This is a string, with both spaces and commas, for testing.]
   [This]
   [is]
   [a]
   [string]
   [with]
   [both]
   [spaces]
   [and]
   [commas]
   [for]
   [testing.]

【讨论】:

    【解决方案2】:

    谢谢!我环顾四周,发现问题出在我的 scanf 上,它没有读取用户输入的整行。看来我的 strtok 工作正常,但我用来匹配 strtok 的返回值的值是错误的。 例如,我的 strtok 函数采用“Jeremy whitfield,Ronny Whitfield”并给了我“Jeremy Whitfield”和“Ronny Whitfield”。在我的程序中,我使用 scanf 来接收用户输入>“Ronny Whitfield”,它实际上只是在读取“Ronny”。所以这是我的scanf而不是strtok的问题。 我的虚拟机每次打开时都会卡住,所以我现在无法访问我的代码。

    【讨论】:

    • 我很高兴您使用的是 C 而不是其他垃圾。
    • 顺便说一句,您应该永远使用scanf 输入您无法控制大小的字符串。就缓冲区溢出而言,这是自找麻烦。要么使用具有特定长度的scanf,要么使用具有最大长度的fgets(后者是我的偏好)。