Advertisement

Creating a Console Class

Started by March 02, 2000 04:33 PM
1 comment, last by Joviex 24 years, 9 months ago
I am trying to get a console going for my 2d/3d hybrid engine, and currently I am running into problems when storing something inside the buffer of the console. I have posted what I have so far of the class, and it would seem that the AddChar function is somewhat confused. Specifically, sprintf. The program bombs out whenever I try to put anything to the buffer, and on the sprintf function.

Anyone know if I am doing the right thing here? I mean, it is pretty straightforward string manipulation?

class cConsole { public: // Constructor - takes all the information you need for the buffer cConsole(int Linelength, int Buffersize) {buffersize = Buffersize; linelength = Linelength; sprintf(prompt,"> "); } // Destructor - cleans up behind itself ~cConsole() { } // Class functions char* GetBuffer(); void NewLine() { } void AddChar(int Char) { char input[1]; sprintf(input,"%c",__toascii(Char)); strcat(buffer,input); } void AddChar(char Char) { } void Draw(); void SetPrompt(char* Prompt) { sprintf(prompt,"%s",Prompt); } void ToggleActive() { active = !active; } bool Status() { return (active); } private: int buffersize; int linelength; int charcount; char buffer[1]; char prompt[1]; bool active; };

You might be having problems with the fact that the sprintf() call is trying to terminate the input buffer, but the buffer is only one character long. Additionally, your whole buffer is only one character long (buffer[1]). This means that addchar will add data to unowned memory, bombing out.

I would do this, solving both problems:

#define MAX_BUFFER_SIZE 255


private:
char buffer[MAX_BUFFER_SIZE];
char *buffer_ptr;

In your constructor:

buffer_ptr = buffer[0]; // point the buffer pointer to the start of the buffer

then you can do this

void AddChar(int Char) { *buffer_ptr = __toascii(Char); buffer_ptr++; *buffer_ptr = ''\0''; }

The function does this:

1. takes the value of char, sticks it into the array element pointed to by buffer_ptr.

2. Incrememnts the pointer, pointing to the next array element.

3. terminate the string by putting a ''NULL'' character on the end.

This system still doesn''t check if the buffer has overflown. you could do this, instead:

void AddChar(int Char) { *buffer_ptr = __toascii(Char); if (buffer_ptr < buffer[MAX_BUFFER_SIZE] buffer_ptr++; *buffer_ptr = ''\0''; }

This checks if the buffer_ptr is still lower than the last element of the buffer[] itself, and only increments the ptr if this is true. That way extra characters on the end (in excess of MAX_BUFFER_SIZE characters) are truncated. (cut off)..

I hope this makes sense.
Advertisement
Awesome, makes total sense. Didn''t realize I was playing around with un-inited memory there. Works like a charm, what more can I say but thanks a googleplex.

This topic is closed to new replies.

Advertisement