Issue with removing the last character of a string

Hello all,

I am currently writing a text box class for me to use with the library SFML. However currently I am having an issue with deleting characters. Here is the portion of the code that deals with deleting new characters, and adding new characters:

1
2
3
4
5
6
7
8
9
if (sf::Keyboard::isKeyPressed(sf::Keyboard::BackSpace) && !string.empty()){
	string.erase(string.size() - 1);
}

if (string.size() <= maxCharNumber){
	string.push_back(toAdd);
}

stringText.setString(string);


The issue that I am having is that when I try to erase the last character of the string, the string's size does not change as the last character is instead replaced with a blank character. Because the string's size does not change when deleting, I can no longer delete any more characters because the character that will get deleted is the blank, which it will then be replaced with.

It also produces an error when adding a new character, as the new character is added after the space. The result is that even if you dont put a space, the text look similar to this:
Hel lo

So any ideas on what I can do about this?
Try the new C++11 string member pop_back instead.
pop_back results in the same error unfortunately. I've already tried pop_back, resize, substr, and erase
I don't believe you. Try printing out string.size() before and after.
Adding character with no previous chars:
1
2
before: 0
after: 1


Adding character with 1 previous chars:
1
2
before: 1
after: 2


deleting character with 2 previous chars:
1
2
3
4
before: 2
after: 1
before: 1
after: 2


deleting character with when there should only be 1 chars:
1
2
3
4
before: 2
after: 1
before: 1
after: 2


Ahh okay, I think I know what's the issue. When I declared toAdd I set it to ' ' by default. When debugging I stupidly only focused on the if statement that removes characters and ignored the part that adds them.

I just fixed it by creating a bool that is set to true if a character needs to be added, and made the if only run if it the bool is true.

Thanks!
Topic archived. No new replies allowed.