Here is a further improved version of the function. This eliminates one more problem that existed with the original code: If you type very fast, then dbGetEntry can return more than one character at the same time, but the character count was only increased by one. This makes the character count incorrect sometimes, with the result that when Backspace is pressed the next time, more than one character is deleted back. What's worse, the code could overwrite the end of the array with an incorrect character count. In this version, I added the characters from the input string one by one, to avoid this issue.
I tested this function together with a 3D object which was moved up/down with the keyboard, to make sure that the function does not disturb detection of the keystates later in the loop.
This function does not watch the return key. It depends on how the program is organized, the return key can be watched from the main program (the code that calls the function) or maybe you can add code to the function to return a true/false flag to indicate when return has been pressed.
void GetInput(char* Buffer, int MaxChars)
{
char* NewEntry = dbGetEntry();
// dbGetEntry returns zero before the first character is typed.
if (NewEntry > 0) {
// Afterwards, the returned pointer is not zero but the string can be empty.
if (NewEntry[0] != 0) {
dbClearEntryBuffer();
int CurLength = strlen(Buffer);
// There can be more than one characters in the returned string
// if the user types fast. Add the characters one by one.
int NewLength = strlen(NewEntry);
for (int i = 0; i < NewLength; i++) {
// Backspace: remove the last character from the string
// if there is still any left.
if (NewEntry[i] == 8) {
if (CurLength > 0) CurLength--;
// Otherwise: add the character if the buffer is not full yet.
} else if (CurLength < MaxChars - 1) {
Buffer[CurLength] = NewEntry[i];
CurLength++;
}
}
// Close the string with a null terminator.
Buffer[CurLength] = 0;
}
// Free memory.
delete[] NewEntry;
}
}
Calling the function:
const int NUM_CHARS = 50;
char Entry[NUM_CHARS];
GetInput(Entry, NUM_CHARS);
Feedback is welcome.
(EDITED because I accidentally left one surplus line in the function and because the space for the null terminator was not taken into account in the previous version.)