Splitting char arrays

Problem statement:
I need to input text from a file into a char array, split the char array at points defined by a delimiting character, and store the sub arrays in a struct ultimately.
The text in the file is formatted like this:

Author: Publisher: Title: Comment | key1 | key2 | key3'\n'

The '|' are the important delimiters, I may use the colons to split for display purposes later.
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
 song ts;
     ifstream fin;
     for(int i = 0; i < 4; ++i)
     {
          ts.info[i] = new char[max];
     }
     char * temp = new char[max];

     fin.open("datafile.txt");
     if(fin)
     {
          fin.get(temp, max, '\n');
          fin.ignore('|', '\n');
          while(!fin.eof())
          {
               fin >> temp;
               fin.ignore('|', '\n');
               
               
               fin.get(temp, max, '\n');
               fin.ignore('|', '\n');
          }
     }
     else
     {
          cout << "File open failed!! \n";
     }


I have to use char arrays and <cstring>- no vectors, strings, etc.
The struct will ultimately be fed into another object- in this file, I will want to loop, overwriting the struct with each new line.
I don't really understand how to manipulate the temp char array to get just the the substrings I need into the struct, but more importantly, I'm not really clear on what's happening as far as getting the text from the file into the temp array.
Any help, advice, and explanations are both sorely needed and much appreciated!
char derp[] = "Author: Publisher: Title: Comment | key1 | key2 | key3"
char *chunk1 = derp;
char *chunk2 = strstr(derp, "|");
*chunk2=0; chunk2++;
char *chunk3 = strstr(chunk2, "|");
...

loop that logic, perhaps.
there are also tricks you can play with getline's delimter, the default is \n but you can override it to get pieces (but its tricksy for multiple delimiters).

this is lazy and destructive. derp is damaged, but the extracted strings are fine. Derp must exist as the other strings are just offsets into the original. But it is extremely effiicent: no copying or extra memory, and really just one pass over the data since the strstr stops when it finds one and resumes from where it left off. C++ strings make it annoying to be this efficient, actually; destructive parsing is one of a very small # of cases where cstrings are a little more friendly.
Last edited on
Topic archived. No new replies allowed.