Krow Caw
Krow Caw

Reputation: 47

Strtok returns wrong data

I have encountered a weird issue with strtok() and I was wondering if you could explain to me what is going wrong. This is just a test program to see if I can get the character `'/`` assigned to a variable so I can run some code later.

(to be specific, my intention is to recognize when a user wants to run a terminal command, so to make sure it is one, I want to use / as first character so I can system() the remaining string)

Anyhow, this is my code.

#include <stdio.h>

int main()
{
char msg[256];
fgets(msg,256,stdin);
char character[256];

character[0] = strtok(msg,"/");
printf("\n%c --> this is the output", character[0]);

return 0;
}

the results vary, printf() may print null, the letters q, a , the character ! or an unrecognizable characters.

/test                                                                                                                                

� --> this is the output

Upvotes: 0

Views: 309

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

Read the man page. strtok() returns a pointer, not a char.

The strtok() and strtok_r() functions return a pointer to the next token, or NULL if there are no more tokens.

You cannot assign a pointer to a char variable.

That said, the code does not do what it is supposed to do. strtok() returns a pointer to the next token, it does not include the delimiter.

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This string does not include the delimiting byte. [...]

Instead, you may want to look at strchr().

Upvotes: 1

Related Questions