Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: String erase problem while using Event::TextEntered  (Read 1182 times)

0 Members and 1 Guest are viewing this topic.

Daaa22

  • Newbie
  • *
  • Posts: 1
    • View Profile
    • Email
String erase problem while using Event::TextEntered
« 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?

G.

  • Hero Member
  • *****
  • Posts: 1592
    • View Profile
Re: String erase problem while using Event::TextEntered
« Reply #1 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.
« Last Edit: March 20, 2022, 07:38:00 pm by G. »