为什么函数strtok改变这样的输入? [英] Why is strtok changing its input like this?

查看:125
本文介绍了为什么函数strtok改变这样的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,我明白的strtok修改其输入参数,但在这种情况下,它的倒塌下来的输入字符串只有第一个令牌。为什么会这样,我能做些什么来解决这个问题? (请注意,我说的不是变量TEMP,其中的是第一个标记,而是变量输入,一个呼叫后函数strtok变成本)

 的#include<&string.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&stdio.h中GT;INT主(INT ARGC,CHAR *的argv []){
   字符输入[] =这是tokenizor七测试;
   字符*温度;
   TEMP = strtok的(输入,);
   的printf(输入:%S \\ n,输入); //输入现在只需本
}


解决方案

的strtok()发现一个道理,令牌到<$后立即改变性格C $ C> \\ 0 ,然后返回一个指向该标记。你用 NULL 参数调用它下一次,它启动终止第一个标记分隔符照顾 - 即 \\ 0 <后/ code>,并有可能走得更远。

现在,原来指向字符串的开头仍指向字符串的开头,但第一个标记是现在 \\ 0 封端的 - 也就是说, 的printf()认为令牌到底是字符串的结尾。该数据的其余部分仍然存在,但 \\ 0 停止的printf()从显示它。如果你使用了 -loop走过去原始的输入字符串到原来的数目的字符,你会发现数据是所有仍然存在。

Ok, so I understand that strtok modifies its input argument, but in this case, it's collapsing down the input string into only the first token. Why is this happening, and what can I do to fix it? (Please note, I'm not talking about the variable "temp", which should be the first token, but rather the variable "input", which after one call to strtok becomes "this")

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char* argv[]) {
   char input[]="this is a test of the tokenizor seven";
   char * temp;
   temp=strtok(input," ");
   printf("input: %s\n", input); //input is now just "this"
}

解决方案

When strtok() finds a token, it changes the character immediately after the token into a \0, and then returns a pointer to the token. The next time you call it with a NULL argument, it starts looking after the separators that terminated the first token -- i.e., after the \0, and possibly further along.

Now, the original pointer to the beginning of the string still points to the beginning of the string, but the first token is now \0-terminated -- i.e., printf() thinks the end of the token is the end of the string. The rest of the data is still there, but that \0 stops printf() from showing it. If you used a for-loop to walk over the original input string up to the original number of characters, you'd find the data is all still there.

这篇关于为什么函数strtok改变这样的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆