首页 > 解决方案 > 如何使用 sscanf 提取子字符串?

问题描述

我有一个文件,其中行具有类似的格式,如下所示:

id: 1   address: tcp://localhost:8101
id: 2   address: tcp://128.134.59.1:8102

现在,对于每一行,我想提取从 tcp 开始的所有内容,直到行尾。我尝试一一读取文件并为此使用 sscanf ,但似乎我的模式匹配是错误的,因为它从不匹配。匹配从 tcp 开始一直到行尾的子字符串的正确方法是什么?

  char **id = malloc(sizeof(char *) * (nodes + 1));
  for (size_t i = 0; i < nodes; i++) {
    char *inter_id = calloc(25, sizeof(char));
    if ((read = getline(&line, &len, fp)) != -1) {
        if (1 != sscanf(line, "%(tcp:*)", inter_id)) {
        fprintf(stderr, "Error: could not parse the address.\n");
        exit(1);
      }
    }
    id[i] = inter_id;

 }
 id[nodes] = NULL;

标签: c

解决方案


id这对我有用,假设每行的, number 和之间的空格数address...是相同的。

int main() {
    FILE* file = fopen("file.txt", "r");
    char buffer[100];
    for (int i = 0; i < 2; i++) {
        int id;
        // The reading is below. %d refers to the number that will be stored in
        // the variable id. %s refers to the char sequence that will be stored in
        // the memory pointed by buffer.
        fscanf(file, "id: %d   address: %s\n", &id, buffer);
        printf("%s\n", buffer);
    }
    fclose(file);
}

file.txt包含两行:

id: 1   address: tcp://localhost:8101
id: 2   address: tcp://128.134.59.1:8102

程序输出:

tcp://localhost:8101
tcp://128.134.59.1:8102

推荐阅读