title: C using strtok to parse an input file
body: <p>Currently trying to parse an input file in C to extract variables. </p>
  
  <p>The input file looks like:</p>
  
  <pre><code>% this is a comment
  x 3
  % another comment
  y 5.0
  % one last comment
  z 4
  </code></pre>
  
  <p>x, y and z are predefined variables in my C class. My goal is to parse this file so that int x has the value 3, y has the value 5.0, and z has the value 4. Any line starting with % is ultimately ignored</p>
  
  <p>I've managed to do this using fgets and sscanf - here is the attempt:</p>
  
  <pre><code>while (!feof(inputFile)) {
      fgets(ch,500,inputFile);
      if (sscanf(ch, "x %d", &amp;x)) {
          printf("x: %d\n", x);
      } else if (sscanf(ch, "y %lf", &amp;y)) {
          printf("y: %lf\n", y);
      } else if (sscanf(ch, "z %d", &amp;z)) {
          printf("z: %d\n", z);
      }
  </code></pre>
  
  <p>and this prints out the desired results. However now I'm trying to use fgets and strtok because I don't think I can get the above code to work with a matrix (i.e. if I had in the input file (note in this case a will also be predefined in my c file):</p>
  
  <pre><code>a
  1 -1 3
  2 1 6
  9 3 0
  </code></pre>
  
  <p>I would like to store those values in a 3x3 matrix which I don't think is possible using sscanf (especially if the matrix dimensonality is changeable - however it will always be an n * n matrix). My attempt with using fgets and strtok is:</p>
  
  <pre><code>while (!feof(inputFile)) {
      fgets(ch,500,inputFile);
      token = strtok(ch, " ");
      while (token) {
          if (strcmp(token, "x")) {
              printf("%s", "x found");
              // Here is my problem - how do I look at the next token where the value for x is stored
  
          }
          token = strtok(NULL, " ");
          break;
  }
      break;
  }
  </code></pre>
  
  <p>The problem in my code is stated in a comment. I've been thinking about this for a while, trying various things. I think the difficulty comes from understanding how strtok works - initially I was trying to store every token into an array.</p>
  
  <p>Any help is appreciated in helping me work out how I can replicate my existing code to use strtok instead of sscanf so I can then work on parsing matrices.</p>
  
  <p>I know there's a few parsing questions out there but I've seen none that tackle how to parse a matrix as such.</p>
  
  <p>Thanks</p>