String - Out of range

When i delete the last character in the string I get the error "string is out of range". I understand why I get the error because when I press backslash theres not a character to delete so the string goes out of range.
But I dont really know how to fix this issue and I would be very happy if someone could help me.

Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  if (event.type == sf::Event::TextEntered)
		{
			if (saveSystem.CharacterName == "")
			{
				if (event.text.unicode < 128)
				{
					name += static_cast<char>(event.text.unicode);
				}
				else if (saveSystem.CharacterName > "")
				{
					if (event.text.unicode == '\b')
					{

						name.erase(name.size() - 1, 1);
						this->characterName->setString(name);


					}
				}
			}
			else
			{
			}
			break;
		}
Last edited on
You should check whether name.size() > 0:

if ((event.text.unicode == '\b') && (name.size() > 0))
You can also use name.pop_back() instead of name.erase(name.size() - 1, 1). You still need to check that name.size() > 0, though.
thanks for the answer!
But I still get the same error, I have try to implement your tips and worked around them but I still get the error.

The code look like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
if (event.type == sf::Event::TextEntered)
		{
			if (saveSystem.CharacterName == "")
			{
				if (event.text.unicode < 128)
				{
					name += static_cast<char>(event.text.unicode);
				}
				else if (saveSystem.CharacterName == "")
				{
					if ((event.text.unicode == '\b') && (name.size() > 0))
					{


						name.pop_back();
						this->characterName->setString(name);
					}
				}
			}
			else
			{

			}
			break;
		}
Last edited on
Can you put your problem into a small stand-alone program involving just one std::string and post it? All these custom type, methods, members might be obfuscating the issue. Doing this exercise might also help you pin-point the problem yourself:
Originally Posted by Bjarne Stroustrup (2000-10-14)

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
Topic archived. No new replies allowed.