programming.nbk: Home | Index | Next Page: Code: CommandLineToArgvA | Previous Page: Code Vault


 Code: break apart a tab or pipe delimited line of text

Header

The size of the array is hard coded at 100.

class line_breaker {
    int     size;       // total number of array locations allocated
    int     next;       // next available location
    char  **array;
public:
            line_breaker(char *line, char* break_char);
           ~line_breaker();
    int     count() { return next; };
    char   *element(int i);
    char   *operator[] (unsigned i) { if (i < next) return array[i]; else return NULL; };
    void    dump(FILE *outfile);
};

Code

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

#include "line_breaker.h"

//##############################################################################
line_breaker::line_breaker(char *line, char *break_char)
{
    next  = 0;
    size  = 100;
    array = new char *[size];
    
    int i = 0;
    
    while (line[i] > '\0') {
        char    temp[100];
        int     j = 0;
        
        while (line[i] > '\0' && !strchr(break_char, line[i])) {
            temp[j++] = line[i++];
        }
        temp[j] = '\0';
        array[next] = strdup(temp);
        next ++;

        if (strchr(break_char, line[i])) i++;
    }
//    for (i = 0; i < next; i++) {
//        printf("%4d: %s\n", i + 1, array[i]);
//    }
}

//##############################################################################
line_breaker::~line_breaker()
{
    for (int i = 0; i < next; i++) {
        delete array[i];
    }
}

//##############################################################################
char *line_breaker::element(int i)
{
    if (i < next) {
        return array[i];
    }
    return NULL;
}

//##############################################################################
void line_breaker::dump(FILE *outfile)
{
    for (int i = 0; i < next; i++) {
        fprintf(outfile, "%4d: %s\n", i + 1, array[i]);
    }
}

programming.nbk: Home | Index | Next Page: Code: CommandLineToArgvA | Previous Page: Code Vault


Notebook exported on Monday, 7 July 2008, 18:56:06 PM Eastern Daylight Time