问题
I am trying to use strtok()
. Following is the piece of code that I wrote. It does not work but prints ", '"
infinitely.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char str[]="this, by the way, is a 'sample'";
char *tokens;
tokens = strtok(str, ", '");
//printf("%s\n",tokens);
//printf("%s\n", str);
while(tokens!=NULL)
{
printf("%s\n", tokens);
tokens = (NULL, ", '");
}
return 0;
}
Following is the code from a strtok()
manual page, which works perfectly fine.
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
I feel I have done the exact same thing. Can't figure out the fault in my code. Could someone please point out.
回答1:
Interesting bug! You forgot function name. Notice inside while-loop body following expression:
tokens = (NULL, ",'");
^
'strtok' missing
should be:
tokens = strtok(NULL, ",'");
Interesting thing is that this is not a compilation error, in fact:
tokens = (NULL, ",'");
is a valid expression which is equals to:
tokens = ",'";
(Note: NULL
has no side effects)
Read: Comma Operator: ,
The comma operator
,
hasleft-to-right associativity
. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before theright operand is evaluated
.
Due to parenthesis (
)
at rhs of =
, after evaluating ,
operator right hand operand ","
is assigned to token
. And because token
never assigned NULL
so while(tokens != NULL)
never breaks, and this is the reason that you are getting ","
infinitely!
来源:https://stackoverflow.com/questions/17896507/strtok-usage-code-not-working