【问题标题】:Parse variable number of differently typed integers from a line in C从C中的一行解析可变数量的不同类型整数
【发布时间】:2017-08-24 00:34:03
【问题描述】:

我有一个文件,其中的行由 '\n' 分隔,其中每一行看起来都像

10010 0 19 7 18

10014 -1 -1 -1 11 10db8 1

也就是说,每一行总是有 5 个或 7 个空格分隔的值,并且每个值的类型也是预先知道的。我想逐行读取文件并解析每一行以提取 inttypes(SCNi32、SCNu32、SCNx32 ..)并存储在相应的 inttype 变量中。最简单的方法是什么?我是 C 新手。

【问题讨论】:

  • 正确的方法是阅读C库参考,找出你需要使用哪些函数,然后使用它们。您似乎已经准备好了一个计划,只需执行它。

标签: c parsing arguments scanf fgets


【解决方案1】:
  1. 使用fgets() 读取行,通过将行分解为标记来解析行。

  2. 使用strtok() 将行分成标记。

  3. 使用atoi() 或任何其他字符串将令牌转换为整数。

【讨论】:

    【解决方案2】:

    您可能应该创建一个结构来存储它们,例如:

    typedef struct
    {
      int16_t   a;
      uint32_t  b;
      int8_t    c;
      ...
    } int_stuff_t;
    

    然后你可以写一个很长的列表比如

    #define GET_FORMAT_SPECIFIER(type) _Generic((type), \
      int16_t:  "%"SCNd16, \
      uint32_t: "%"SCNu32, \
      int8_t:   "%"SCNd8)
    
    fscanf(fp, GET_FORMAT_SPECIFIER(int_stuff.a), &int_stuff.a);
    fscanf(fp, GET_FORMAT_SPECIFIER(int_stuff.b), &int_stuff.b);
    ...
    

    现在,如果您有很多这些并且它们具有各种名称和格式,那么这可能是您应该考虑使用 X 宏以使代码易于维护的少数有效情况之一。

    例子:

    #include <stdio.h>
    #include <stdint.h>
    #include <inttypes.h>
    #include <assert.h>
    
    // X macro (type, name, format)
    #define INT_STUFF_LIST     \
      X(int16_t,  a, SCNd16)   \
      X(uint32_t, b, SCNu32)   \
      X(int8_t,   c, SCNd8)
    
    typedef struct
    {
      #define X(type, name, format) \
      type name;
      INT_STUFF_LIST
      #undef X
    } int_stuff_t;
    
    int main()
    {
      FILE* fp = fopen("something.txt", "r");
      assert(fp != NULL);
    
      int_stuff_t int_stuff;
    
      #define X(type, name, format) \
      fscanf(fp, "%" format, &int_stuff.name);
      INT_STUFF_LIST
      #undef X
    
      fclose(fp);
    }
    

    虽然这只是一个快速而肮脏的示例,但实际代码应该不断检查每个 fscanf 调用的结果,以确保它不是 EOF。

    【讨论】:

      猜你喜欢
      • 2016-10-12
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 2018-11-07
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      相关资源
      最近更新 更多