Allowing backspace only on the last item entered

Hi, I've been having trouble figuring out how to allow backspace only on the last item entered. I was trying to modify some codes on the psychtoolbox function 'GetEchoString'. In this function, it allows backspacing for all items entered:
string = '';
while true
char = GetChar;
switch (abs(char))
case {13, 3, 10}
% ctrl-C, enter, or return
break;
case 8
% backspace
if ~isempty(string)
string = string(1:length(string)-1);
end
otherwise
string = [string, char ' '];
end
But I just want to allow backspacing only on the last item entered. (i.e.: case 8 cannot be entered twice in a row).
How do I do that?
Thanks in advance!

 Risposta accettata

string = '';
last_was_bs = false;
while true
char = GetChar;
switch (abs(char))
case {13, 3, 10}
% ctrl-C, enter, or return
break;
case 8
if ~last_was_bs
% backspace
if ~isempty(string)
string = string(1:length(string)-1);
end
end
last_was_bs = true;
otherwise
string = [string, char ' '];
last_was_bs = false;
end
However, I don't think you are going to find this very suitable. The extra space that is inserted after every character increases the length of the string, and would thus be what was trimmed out by the first backspace. In order to be able to actually remove the last character typed, the user needs to be able to type at least two backspaces. Unless, that is, the extra space was not added.
It is poor programming practice to name a variable "char", as that interferes with using the MATLAB char() function.

1 Commento

Thanks for your help! It works out well.
I just had to change the length(string) to minus 2 instead of minus 1.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by