C-如何在文本文件中分割一行并存储其值?

时间:2019-02-25 19:43:07

标签: c split fgets

假设我的文本文件中有多行:

print 1
set_flag 1 2 1
find_path 7 8
print 5

我希望能够分离这些值并将其应用于我的功能:

void print(int id) {...}
void set_flag(int a, int b, int c) {...}
void find_path(int from, int to) {...}

这就是我现在被困住的地方:

char str[256];
while(fgets(str, 256, filename) != NULL){
    //if a line contains "set_flag" then call set_flag(int a, int b, int c)
    if((strstr(str, "set_flag")) != NULL){
        //retrieve the str and all individual int values
        ...
    }
}

我在网上看了一下,发现使用strcmp,strstr,strtol和fscanf的建议。尽管该分配建议使用strtol将文本文件中的可读值转换为“正确”数据类型。

1 个答案:

答案 0 :(得分:0)

您可以保存匹配的子字符串的指针,然后在该子字符串的末尾插入NUL((ComplexDataStructure -> a))字符,这样可以有效地将字符串分成两个单独的字符串。

但是,由于您真正需要的只是字符串的其余部分在匹配的“ set_flag”之后的位置,以便检索整数值,因此您不必这样做。相反,您只需在字符串中找到该位置:

double :: (ComplextDataStructure -> a) -> (ComplexDataStructure -> b) -> ( (a, b) -> c) -> ComplexDataStructure -> c

这时,指针'\0'指向您从输入中读取的文本行中'set_flag'之后的字符。然后,您可以使用// if a line contains "set_flag" then call set_flag(int a, int b, int c) char *p = strstr(str, "set_flag"); if (p != NULL) { // str contains 'set_flag', which p now points to p += strlen("set_flag"); // p now points to the rest of the string following 'set_flag' // retrieve the individual int values from the rest of the string ... // left as an exercise, sscanf(p, ...) ... } 从字符串中提取整数值(我将为您做练习)。