我有一个想要在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, " "),";");
虽然这个代码稍后会带来分段错误,所以我跟着调试器注意到第二个代码行没有正确执行。
帮助?
答案 0 :(得分:3)
这些陈述
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
的说明。
考虑到在函数中通过插入提取的子字符串的终止零来更改原始字符串,并且该函数在插入的终止零之后保留原始字符串的下一部分的地址,直到它将被调用第一个参数不等于NULL ..
答案 1 :(得分:1)
您可以像这样使用strtok()
来收集有关每行的信息:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char string[] = "paris pidgey pikachu; london berlin";
char *city = strtok(string, " ");
printf("city: %s\n", city);
char *pokemon_names = strtok(NULL, ";");
printf("pokemon names: %s\n", pokemon_names);
char *near_cities = strtok(NULL, "\n");
memmove(near_cities, near_cities+1, strlen(near_cities)); /* removes space at start of string */
printf("near cities: %s\n", near_cities);
return 0;
}
输出:
city: paris
pokemon names: pidgey pikachu
near cities: london berlin
这实际上取决于你如何存储这些字符串。