在C的嵌套循环中使用strtok()? [英] Using strtok() in nested loops in C?
本文介绍了在C的嵌套循环中使用strtok()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在嵌套循环中使用 strtok()
,但这没有给我想要的结果,可能是因为它们使用相同的内存位置.我的代码格式为:-
I am trying to use strtok()
in nested loops but this is not giving me desired results,
possibly because they are using the same memory location. My code is of the form:-
char *token1 = strtok(Str1, "%");
while (token1 != NULL)
{
char *token2 = strtok(Str2, "%");
while (token2 != NULL)
{
//Do something
token2 = strtok(NULL, "%");
}
// Do something more
token1 = strtok(NULL, "%");
}
推荐答案
是的, strtok()
实际上使用一些静态内存来保存两次调用之间的上下文.如果使用的是VS,则使用 strtok()
, strtok_r()
的可重入版本,或者使用 strtok_s()
strtok_r()).
Yes, strtok()
, indeed, uses some static memory to save its context between invocations. Use a reentrant version of strtok()
, strtok_r()
instead, or strtok_s()
if you are using VS (identical to strtok_r()
).
它还有一个附加的上下文参数,您可以在不同的循环中使用不同的上下文.
It has an additional context argument, and you can use different contexts in different loops.
char *tok, *saved;
for (tok = strtok_r(str, "%", &saved); tok; tok = strtok_r(NULL, "%", &saved))
{
/* Do something with "tok" */
}
这篇关于在C的嵌套循环中使用strtok()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文