奇怪的strtok行为

时间:2013-09-02 00:53:45

标签: c strtok

我一直在尝试使用strtok来编写多项式微分程序,但它似乎表现得很奇怪。在这一点上,我已经告诉它停止角色'',[,],(和)。但由于某种原因,当传递诸如“Hello []”之类的输入时,它返回“Hello \ n”

我的代码在这里有什么问题吗?所有多项式字符串都是文本“Hello []”

void differentiate(char* polynomial) 
{
    char current[10];
    char output[100];

    strncpy(current, strtok(polynomial, " []()/\n"), 10);
    printf("%s", current);

} // differentiate()
编辑:它似乎是一个与shell有关的问题,毕竟它似乎也不是换行符,因为当我使用bash时它不会发生,但是当我使用fish时,我得到以下内容:

enter image description here

我以前从未见过这种事,有没有人有任何建议?这只是鱼的怪癖吗?

1 个答案:

答案 0 :(得分:2)

我将您的代码转换为此SSCCE(Short, Self-Contained, Correct Example):

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

static
void differentiate(char* polynomial) 
{
    char current[10];

    strncpy(current, strtok(polynomial, " []()/\n"), 10);
    printf("<<%s>>\n", current);

}

int main(void)
{
    char string[] = "Hello[]";
    printf("Before: <<%s>>\n", string);
    differentiate(string);
    printf("After:  <<%s>>\n", string);
    return 0;
}

实际输出:

Before: <<Hello[]>>
<<Hello>>
After:  <<Hello>>

我在Mac OS X 10.8.4上使用GCC 4.8.1进行测试,但我在Apple提供的GCC(i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00))和clangApple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)上获得了相同的结果)。

您应该通过调整此测试并显示输出,证明您断言strtok()中有换行符。请注意代码如何使用<<>>来包围正在打印的字符串;如果那里有换行符,它将显示在双尖括号内。

相关问题