Note that there are some explanatory texts on larger screens.

plurals
  1. POParsing string based on initial format
    primarykey
    data
    text
    <p>I'm trying to parse a set of lines and extract certain parts of the string based on an initial format (reading a configuration file).</p> <p>A little more explanation: the format can contain up to <em>4</em> parts to be formatted. This case, <code>%S</code> will skip the part, <code>%a-%c</code> will extract the part and will be treated as a string, <code>%d</code> as int.</p> <p>What I am trying to do now is to come up with some clever way to parse it. So far I came up with the following prototype. However, my pointer arithmetic still needs some work to skip/extract the parts.</p> <p>Ultimately each part will be stored on an array of structs.</p> <p><strong>Edit:</strong> using <code>sscanf</code> might not work in this case, since the format is specified in a configuration file. Additionally, the format could scale, string (and type) may change.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #define DIM(x) (sizeof(x)/sizeof(*(x))) void process (const char *fmt, const char *line) { char c; const char *src = fmt; while ((c = *src++) != '\0') { if (c == 'S'); // skip part else if (c == 'a'); // extract %a else if (c == 'b'); // extract %b else if (c == 'c'); // extract %c else if (c == 'd'); // extract %d (int) else { printf("Unknown format\n"); exit(1); } } } static const char *input[] = { "bar 200.1 / / (zaz) - \"bon 10\"", "foo 100.1 / / (baz) - \"apt 20\"", }; int main (void) { const char *fmt = "%S %a / / (%b) - \"%c %d\""; size_t i; for(i = 0; i &lt; DIM (input); i++) { process (fmt, input[i]); } return (0); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload