Dynamic String Input

seanbp 0 Tallied Votes 329 Views Share

These days, it's usually unnecessary to consider how much memory to allocate for a string input. This was mostly for fun. This code allocates memory as the user inputs each key stroke, then allocates and returns a string pointer when the user presses enter. Tell me what you think!

USAGE:

int main(){
    char* string = getline();
    std::cout << string << std::endl;
}

Also, here I've copied a nonmodular version of getch():

int getch() {
    int ch;
    struct termios oldt;
    struct termios newt;
    tcgetattr(STDIN_FILENO, &oldt); /*store old settings */
    newt = oldt; /* copy old settings to new settings */
    newt.c_lflag &= ~(ICANON | ECHO); /* make one change to old settings in new settings */
    tcsetattr(STDIN_FILENO, TCSANOW, &newt); /*apply the new settings immediatly */
    ch = getchar(); /* standard getchar call */
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt); /*reapply the old settings */
    return ch; /*return received char */
}
class LinkedString {
    class Item {
    public:
        Item* previous;
        Item* next;
        char ch;
    };
    Item* data_begin;
    Item* data;
    Item* data_end;
    int len;
public:
    LinkedString() {
        len = 0;
    }
    ~LinkedString() {
        if (len == 0) return;
        Item* temp;
        data = data_begin;
        while (data != data_end) {
            temp = data;
            data = data->next;
            delete temp;
        }
        delete data;
    }
    void add(char i) {
        data = new Item;
        if (len == 0) {
            data_begin = data;
            data_end = data;
        } else {
            data->previous = data_end;
            data_end->next = data;
            data_end = data_end->next;
        }
        data_end->ch = i;
        len++;
    }
    void backspace() {
        Item* temp = data_end;
        data_end = data_end->previous;
        delete temp;
        len--;
    }
    char* get_string() {
        char* string = new char[len+1];
        char* string_begin = string;
        data = data_begin;
        for (int i = 0; i < len; i++) {
            *string++ = data->ch;
            data = data->next;
        }
        *string = 0;
        return string_begin;
    }
};

char* getline() {
    LinkedString string;
    int ch;
    while ((ch = getch()) != 10) {
        if (ch == 127) {
            std::cout << "\b \b";
            string.backspace();
        } else {
            string.add((char) ch);
            std::cout << (char) ch;
        }
    }
    std::cout << "\n";
    return string.get_string();
}