How to parse text file into 3dimensional dynamical array

I have a file, that has peaces of data separated by new lines and comas, it looks like this:

Time,Name,Longitude,Altitude
17:00,John,56.535,58.75
16:00,Peter,58.68,78.10

or like this:

Id,Name,Price,In stock
01,Tooth Brush,5.15,5
02,Tooth Paste,6.99,10
03,Pencil,1.10,100
04,Pins,5.00,10

I need to parse this information into char arrays. For instance in first array values[1][2] should be "56.535" values[0][2] - "Longitude", etc.
Now I've written code for this, but it (as I expected) doesn't work after hour of struggle I decided to ask for help. Can someone tell me what's wrong with this code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

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

using namespace std;

int main()
{
    FILE* input;
    FILE* output = fopen("output.txt", "w");
    char current_char = 0;
    int rows = 0;
    int cols = 0;
    int cell_size = 0;
    char *** values = new char**[1];
    values[0] = new char*[1];
    values[0][0] = new char[1];
    char* file_name = new char[256];
    cout << "Enter the name of the file" << endl;
    cin >> file_name;
    cout << endl;
    input = fopen (file_name, "r");
    while (!feof(input))
    {
        current_char = getc(input);
        switch (current_char)
        {
            case 10:
                rows++;
                cout << "Rows: "<< rows << endl;
                cell_size = 0;
                cols = 1;
                values = (char***) realloc(values, rows * sizeof(char**));
                break;
            case 44:
                cols++;
                cout << "Cols: "<< cols << endl;
                cell_size = 0;
                values[rows-1] = (char**) realloc(values[rows-1], cols * sizeof(char*));
                break;
            default:
                cell_size++;
                cout << "Cell_size: " << cell_size << endl;
                values[rows-1][cols-1] = (char*) realloc(values[rows-1][cols-1], cell_size * sizeof(char));
                values[rows-1][cols-1][cell_size-1] = current_char;
        }
    }
    fclose(input);
    fclose(output);
}
Last edited on
Topic archived. No new replies allowed.