strtok的用法,code不工作 [英] Strtok usage, code not working
问题描述
我想使用的strtok()
。以下是我写的一张code的。它不工作,但打印,
无限。
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;
}
以下是从的strtok()
手册页,这工作完全正常的code。
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;
}
我觉得我也做了同样的事情。在我的code不能找出故障。可能有人请指出。
I feel I have done the exact same thing. Can't figure out the fault in my code. Could someone please point out.
推荐答案
有趣的错误!你忘了函数名。注意里面而环体下面的前pression:
Interesting bug! You forgot function name. Notice inside while-loop body following expression:
tokens = (NULL, ",'");
^
'strtok' missing
应该是:
tokens = strtok(NULL, ",'");
有趣的是,这是不会编译错误,事实上:
tokens = (NULL, ",'");
是一个有效的前pression这等于:
is a valid expression which is equals to:
tokens = ",'";
(注: NULL
有没有副作用)
阅读:逗号操作:,
逗号操作符,
的左到右联
。两位前pressions
用逗号分隔的是从左向右。左操作数
始终评估,所有副作用的权前完成
。
操作数评估
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
.
由于括号(
)
在 =
评估后,
运算符的右手操作数,
分配给标记
。而由于标记
从来没有分配 NULL
所以而(令牌!= NULL)
从来没有打破,这就是你得到,
无限的原因!
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!
这篇关于strtok的用法,code不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!