views:

169

answers:

3

Hi!

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

A: 

Why not try if(!mText.empty())mText = mText.substr(0, mText.length()-1);?

Vite Falcon
hm, did not think of substr... but this is not working either. <code>mText.length();</code> does not change
opatut
Why not just `pop_back()`? Or at the least `erase`/`resize` it.
GMan
std::string does not have a pop_back method, sadly ...
opatut
Well I'll be damned.
GMan
@opatut: Well.. If you are using the code as I've given then it shud change it. Unless you're not setting mText to be the text of the text-field or you're re-reading the value of the text-field back into mText just after this statement. And, as GMan said, there's always `pop_back()`. I'm not sure which C++ library you're using here. But if it's standard C++ compliant library, std::string and std::wstring does have pop_back().
Vite Falcon
std::string has pop_back? I don't find it here: http://www.cplusplus.com/reference/string/string/ and my compiler complains about it...
opatut
@opatut @Vite: Indeed, there is no `pop_back`. (In the C++03 standard. There is in the C++0x standard, though I didn't realize that was an addition and is what I had in mind.) All the more reason to claim the standard library is poorly designed; free-functions are better than member functions.
GMan
+1  A: 

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..

Martin Thomas
[OT]Wow, ideone.com is going to be useful, thank you![/OT]
Matteo Italia
Huh. Looks like Codepad.org with more supported languages.
greyfade
A: 

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"
opatut