strtok使用了错误的分隔符

时间:2010-08-10 06:47:15

标签: c delimiter strtok

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

2 个答案:

答案 0 :(得分:7)

我只能建议你做错了,虽然有点难以准确说出什么(通常在询问细节时你应该发布你的代码)。示例程序,如下所示,似乎工作正常:

#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.]

答案 1 :(得分:0)

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

相关问题