字符串解析,纯C

时间:2018-10-05 22:11:52

标签: c parsing arguments token

我有一个动态分配的带有允许标记的数组。在每个令牌用户之后应写一个数字,该数字将用于定义变量的值[$ program --token=99];如何解析最后一个数字?

这是代码:

/* libs */

#define TOKENS_QT 5
#define TOKEN_SIZE 6

static uint8_t GRID_WIDTH;

int main (const int argc, const char* argv[]) {
  if (strncmp(argv[1], "--help", 6)) {
    /* Here is some info about usage. */
    return 0;
  } else if (strncmp(argv[1], "--std", 5)) {
    /* Here is standard set up. */
  } else if (argc == TOKENS_QT + 1) {
    char** tokens = malloc(TOKENS_QT * TOKEN_SIZE);
    tokens = (char* [TOKENS_QT]) { "--sgw=", "--sgh=", "--sdq=", 
                                   "--shq=", "--soq=" };

    for (register uint8_t i = 0; i < TOKENS_QT; ++i) {
      if (strncmp(argv[i + 1], tokens[i], 6)) {
        switch(i) {
          case 0: // --sgw=
            /* some cool actions to parse --sgw=99, for example, into 99 */
            /* some actions to check validity of given number */
            GRID_WIDTH = 99;
            break;
          /* There are other tokens handling. */
        }
      }
    }

    free(tokens);
  } else {
    /* Here is again info about correct usage. */
    return 0;
  }

  return 0;
}

1 个答案:

答案 0 :(得分:0)

您可以使用sscanf()对其进行解析。

sscanf(argv[i + 1], "--sgw=%d", &GRID_WIDTH);

如果您不想在格式字符串中放入--sgw=,则可以执行以下操作:

sscanf(argv[i+1]+6, "%d", &GRID_WIDTH);

添加6会跳过参数中的--sgw=前缀。