Search code examples
c++sfml

cannot get the size of a string in C++ visual studio


I wrote a simple program to delete a letter in a string with backspace to use while typing. It's supposed to get the length of the string each time and delete the last character but I can't get function .length(); to work in my program which I saw it used in stackoverflow by another person.

Event eventInput;
string stringLength;
String userInput;
Text userText;
while (window.pollEvent(eventInput))
{
    if (eventInput.type == sf::Event::TextEntered)
    {
        if (Keyboard::isKeyPressed(Keyboard::Backspace))
        {
            stringLength = userInput.length();
            userInput.erase(1, 1);
        }
        userInput += eventInput.text.unicode;
        userText.setString(userInput);
    }
}

It says sf::String has no member length


Solution

  • The problem is that you (and your code) are mixing up two different types of string. String and string are not the same. It seems you want the SFML string class which is called String. And the method to get the length of an SFML string is called getSize not length.

    You would avoid some of this confusion if you did not add using namespace sf; and using namespace std; to your code.

    Another error in your code is the handling of backspace. Your code deletes a characters when it detects a backspace but then adds it back again. This is because your code has an if statement when it should have an if ... else statement. Like this

    if (Keyboard::isKeyPressed(Keyboard::Backspace))
    {
        stringLength = userInput.length();
        userInput.erase(1, 1);
    }
    else
    {
        userInput += eventInput.text.unicode;
        userText.setString(userInput);
    }
    

    One of the things you will learn is to look at your code and see what it really says.