Alex P
Alex P

Reputation: 530

Odd strtok behavior

I've been trying to use strtok in order to write a polynomial differentiation program, but it seems to be behaving oddly. At this point I've told it to stop at the characters ' ', [, ], (, and ). But for some reason, when passed input such as "Hello[]" it returns "Hello\n"

Is there anything wrong with my code here? All the polynomial string is is the text "Hello[]"

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

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

} // differentiate()

EDIT : It appears to be an issue related to the shell, and it would also appear to not be a newline after all, as when I use bash it does not occur, but when I use fish, I get the following:

enter image description here

I've never seen this kind of thing before, does anyone have any advice? Is this just a quirk of fish?

Upvotes: 0

Views: 243

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753585

I converted your code into this 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;
}

Actual output:

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

I was testing with GCC 4.8.1 on Mac OS X 10.8.4, but I got the same result with the Apple-supplied GCC (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)) and clang (Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)).

You should justify your assertion that you got a newline out of strtok() by adapting this test and showing the output. Note how the code uses the << and >> to surround the string it is printing; if there's a newline in there, it will show up inside the double angle brackets.

Upvotes: 2

Related Questions