我有一个文件要用c读,
文件格式如下:
<city> <pokemon1> <pokemon2>; <near_city1> <near_city2>
例如:
paris pidgey pikachu; london berlin
我希望能够使用strtok将这一行剪切为令牌,但由于某些原因,它不能正常工作。
我的代码:假设我使用fgets从文件中读取这一行,并将其放入char*行。
所以我做的是:
char* city_name = strtok(location_temp, " "); // to receive city
char* pokemons_names = strtok(strtok(location_temp, " "),";");
不过,这段代码稍后会带来分段错误,所以我跟随调试器,注意到第二行代码没有正确执行。
帮忙?
最佳答案
这些声明
char* city_name = strtok(location_temp, " "); // to receive city
char* pokemons_names = strtok(strtok(location_temp, " "), ";");
是有效的,并且如果
location_temp
不等于NULL
并且不指向字符串文本,则不会导致分段错误。但是,此代码段并没有达到您所期望的效果。第一个和第二个语句返回的指针与
location_temp
指向的字符串中初始单词的地址相同。你至少应该写
char* city_name = strtok(location_temp, " "); // to receive city
strtok(NULL, " ");
char* pokemons_names = strtok( NULL, ";");
我认为出现分段错误是因为您没有将结果字符串复制到单独的字符数组中。但是如果没有实际的代码,很难准确地说出原因。
在使用之前,您应该阅读函数
strtok
的说明。考虑到原始字符串是在函数中通过为提取的子字符串插入终止零来更改的,并且函数在插入终止零之后保留原始字符串的下一部分的地址,直到第一个参数不等于空时调用它为止。。
关于c - strtok如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41548447/