Search code examples
cparsingargumentstoken

String parsing, pure C


I have a dynamically allocated array with an allowable tokens. After each token user should write a number, which will be used to define a variable's value [$ program --token=99]; how to parse this last number?

Here is code:

/* 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;
}

Solution

  • You can use sscanf() to parse it.

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

    If you don't want to put --sgw= in the format string, you can do:

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

    Adding 6 skips past the --sgw= prefix in the argument.