本文介绍了在调用strtok的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的strtok这样有一个函数

I have a function using strtok like this

void f1(char *name)
{
...
char *tmp;
tmp = strtok(names, " ,");
while(tmp)
{
...
tmp = strtok(NULL, " ,");
}
...
}

和我有一个呼叫F1(ABC DEF);

And i have a call f1("abc,def");

问题是,在第一次调用F1获得ABC,DEF
并在第二个呼叫刚刚获得美国广播公司

Problem is that in first call f1 gets abc,defand in 2nd call gets just abc

我很困惑。为什么会这样呢?

I am confused.. Why is this so?

推荐答案

的strtok()通过用0覆盖分隔符修改其输入字符串;因此,假设你的code看起来是这样的:

strtok() modifies its input string by overwriting the delimiters with a 0; so, assuming your code looks something like this:

char parm[] = "abc,def";

f1(parm);
f1(parm);

第一呼叫到F1之后,','字符被覆盖了0,这是一个字符串终止子,所以第二呼叫只能看到ABC作为字符串。

after the first call to f1, the ',' character is overwritten with a 0, which is a string terminator, so the second call only sees "abc" as the string.

请注意,由于的strtok()修改它的输入,你不希望传递一个字符串作为参数;试图修改字符串调用未定义行为的内容。

Note that because strtok() modifies its input, you do not want to pass it a string literal as an argument; attempting to modify the contents of a string literal invokes undefined behavior.

在安全的事情是创造F1中的一个局部字符串复制姓名它的内容,然后通过当地字符串的strtok()。以下应与C99工作:

The safe thing to do is to create a local string within f1 and copy the contents of names to it, then pass that local string to strtok(). The following should work with C99:

void f1(char *name)
{
  size_t len = strlen(name);
  char localstr[len+1];
  char *tmp;
  strcpy(localstr, name);

  tmp = strtok(localstr, " ,");
  while(tmp)
  {
    ...
    tmp = strtok(NULL, " ,");
  }
}

这篇关于在调用strtok的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 00:23