Reputation: 6864
I am currently trying to implement deleting characters from a text field in C++. If the user hits Backspace, the following code is executed. There is currently no cursor, it should just remove the last character...
if (mText.length() > 0){
mText.erase( mText.length() - 1, 1);
// mText.resize(mText.length() - 1);
}
This works fine the first time, but if you hit Backspace again, it does not remove anything.
I printed the mText.length()
and it shows that the length never changes. I tried to resize()
the string, it works fine, but the first time I hit Backspace it removes 2 characters.
I hope someone can explain this behaviour and help me solving the problem. I dont know much about memory allocation, so please be patient with me ;)
Thanks
opatut
Upvotes: 2
Views: 3750
Reputation: 6864
I found my problem using gdb. I found the hidden \b
escape sequence which was added to my string after I removed the last character. It actually stands for the backspace, but it was not interpreted. Thank you for your help!
"Roflcopt\b"
Upvotes: 0
Reputation: 6985
According to this, string.erase with a single size_t parameter will remove all characters from the specified position to the end of the string. A second size_t parameter may be provided for the number of characters to be deleted.
I checked this works as expected using http://www.ideone.com (look here) and also checked that string::length() works as expected.
I think the problem is elsewhere..
Upvotes: 2
Reputation: 6645
Why not try if(!mText.empty())mText = mText.substr(0, mText.length()-1);
?
Upvotes: 1