SFML community forums

Help => General => Topic started by: Daaa22 on March 20, 2022, 06:00:23 pm

Title: String erase problem while using Event::TextEntered
Post by: Daaa22 on March 20, 2022, 06:00:23 pm
#include <SFML/Graphics.hpp>
#include <iostream>

using namespace std;
using namespace sf;

int main()
{
    Keyboard keyboard;

    RenderWindow window( VideoMode( 800, 600 ), "..." );

    string help;

    while( window.isOpen() )
    {
        Event event;

        while( window.pollEvent( event ) )
        {
            if( event.type == Event::Closed )
                window.close();

            if( event.type == Event::KeyPressed && keyboard.isKeyPressed( Keyboard::Backspace ) )
            {
                help.erase( help.end() - 1 );
                cout << help << endl;
            }
            else if ( event.type == Event::TextEntered && event.text.unicode < 128 )
            {
                help += static_cast<char>(event.text.unicode);
                cout << help << endl;
            }
        }

        window.display();
    }

    return 0;
}
 

Try running it, type anything you would like and try to use backspace. Used once works good, but if i try to delete second character then nothing changes in my string. How to solve this?
Title: Re: String erase problem while using Event::TextEntered
Post by: G. on March 20, 2022, 07:36:06 pm
In your TextEntered event, don't add the character to your string if it is equals to the backspace character ( '\b' ).

In your current code you delete the last char in the KeyPressed event, and then you also add the backspace character in your TextEntered event, it is probably invisible. On further backspace key presses you delete that invisible character then add a new one. That's why it looks like it's not doing anything.