首页 文章

strtok如何正常工作?

提问于
浏览
0

我有一个我想在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, " "),";");

虽然,此代码稍后会带来分段错误,所以我跟着调试器注意到第二个代码行没有正确执行 .

救命 ?

2 回答

  • 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

    您可以像这样使用 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
    

    这实际上取决于你如何存储这些字符串 .

相关问题