C++从字符串中删除字符

发布于 2024-09-19 17:50:42 字数 454 浏览 5 评论 0原文

我目前正在尝试在 C++ 中实现从文本字段中删除字符。如果用户按下 Backspace,则执行以下代码。当前没有光标,它应该只删除最后一个字符...

if (mText.length() > 0){
    mText.erase( mText.length() - 1, 1);
    // mText.resize(mText.length() - 1);
}

第一次工作正常,但如果您再次按退格键,它不会删除任何内容。

我打印了 mText.length() ,它显示长度永远不会改变。我尝试 resize() 字符串,它工作正常,但是当我第一次按 Backspace 时,它​​会删除 2 个字符。

我希望有人可以解释这种行为并帮助我解决问题。我对内存分配不太了解,所以请耐心等待;)

谢谢
oput

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千笙结 2024-09-26 17:50:42

根据 this,带有单个 size_t 参数的 string.erase 将删除所有从指定位置到字符串末尾的字符。可以为要删除的字符的数量提供第二size_t参数。

我使用 http://www.ideone.com (查看 此处)并检查 string::length() 是否按预期工作。

我认为问题出在其他地方..

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

一抹微笑 2024-09-26 17:50:42

为什么不尝试 if(!mText.empty())mText = mText.substr(0, mText.length()-1);?

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

窗影残 2024-09-26 17:50:42

我使用 gdb 发现了我的问题。我发现隐藏的 \b 转义序列在删除最后一个字符后被添加到我的字符串中。它实际上代表退格键,但没有被解释。感谢您的帮助!

"Roflcopt\b"

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文