0

I have a textfile which contains something like this: 1|2|3|4|5|.......23|24|25

I need to read this file, tokenize the values and enter the values in a 2D array.

for(i=0; i<size; i++) 
{
    for (j=0; j<size; j++)
    {   
        board[i][j] = *buffer;
        buffer++;
    }
}

I need to tokenize the values using "|" as delim and enter the values into the 2D array... Please help. I know the above is not correct, pls help.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

0
  • Read the data from file in a string.

  • Apply string tokenizer on your string and get the separate data.

    For tokenizing the string, take a look at Boost.Tokenizer. It's great. Boost generally has some very cool string tools.
    Once you get separate data you can store it in 2-D array.

Community
  • 1
  • 1
Sachin Mhetre
  • 4,465
  • 10
  • 43
  • 68
0

You could read the whole file into a char * array. I'll assume that's what is in buffer and then use strtok to tokenize with "|".

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

deebee
  • 1,747
  • 13
  • 14
  • I am trying to use strtok but how do I store the seperate data into a 2D format – Apsara Sriram Apr 27 '12 at 06:21
  • how are determining the value "size" variable above? from the code you have provided it looks like the file contains data in row major order and you have the size stored somewhere. – deebee Apr 27 '12 at 06:26
  • initially the size is taken as input from the user..the game board is designed based on that.eg., size 5 draws a 5X5 board. Later when the game is saved, the size is also saved into a file and when the file is read, the board is again drawn on the same size. The prob is where I need to draw the board with the exact player marks before the game was saved. – Apsara Sriram Apr 27 '12 at 06:33
  • how about this to save file fprintf(file, "%d ", size); for(int row = 0; row < size; ++row) for(int col = 0; col < size; ++col) fprintf(file, "%d ", board[row][col]); Now you can read back the file same way using fscanf. – deebee Apr 27 '12 at 06:39
  • Note that I'm using a space in "%d " – deebee Apr 27 '12 at 06:41