0

For my game, I'm creating a tilemap that has tiles with different numeric ids, such as 1, 28, etc. This map data is saved into a .dat file that the user edits, and looks a little bit like this:

0, 83, 7, 2, 4

Now in order for the game to generate the correct tiles, it must see what the map data is obviously. What I want this small parser to do is to skip over whitespace and the commas, and fetch the numeric data. Also, I want it to be in a way that I can get not only single digit id numbers, but 2-3 digits as well (83, etc).

Thanks for any and all help!

Peter
  • 328
  • 4
  • 18
  • This is called *CSV (comma separated values)*. Quite common, though not standardized file format. Search for "parsing CSV". – SChepurin Apr 05 '14 at 12:56
  • This is just a standard exercise in iostream formatted input. You can use `getline` if you like to split by commas. – Kerrek SB Apr 05 '14 at 12:57
  • Actually, that all is overkill. Just use old and temperamental `fscanf()`. Format " %d%*[, \n]" – Deduplicator Apr 05 '14 at 13:11

2 Answers2

0

Sounds like a job for the strtok function:

#include <stdlib.h>
#include <string.h>

int parseData(char* data, size_t maxAllowed, int* parsedData) {
  char * pch;
  pch = strtok (data," ,");
  int idx = 0;
  while (pch != NULL)
  {
    parsedData[idx++] = atoi(pch); //convert to integer
    if (i == maxAllowed) {
      break; //reached the maximum allowed
    }
    pch = strtok (NULL, " ,");
  }
  return i; //return the number found
}

//E.g.
char data[] ="0, 83, 7, 2, 4";
int parsedData[5];
int numFound = parseData(data,5,parsedData);

The above sample will remove all spaces and commas, returning an integer value for each found along with the total number of elements found.

Reading the file could be done easily using C functions. You could read it either all at once, or chunk by chunk (calling the function for each chunk).

Tom Carpenter
  • 539
  • 4
  • 18
0

This is CSV parsing, but easy is in the eye of the beholder. Depends on whether you want to "own" the code or use what someone else did. There are two good answers on SO, and two good libraries on a quick search.

The advantage of using a pre-written parser is that when need some other feature it's probably already there.

Community
  • 1
  • 1
david.pfx
  • 10,520
  • 3
  • 30
  • 63