See how to read text from the user, both from command line and graphical applications.
Written by: Andrew Cain and others Last updated: October 2024
This article shows you how to get started reading text from the user. This includes reading text from the command line but also how to read text from within a graphical application.
Reading Text from the Command Line
Reading text input from the user is straightforward for command line applications. In this context, Read Line allows you to read a line of text entered at the Terminal. This is a blocking function call, meaning it waits for the user to input the line before it returns. For command line applications, this is fine; you want it to wait for the input.
The following code demonstrates the use of Read Line in order to read in and display the user’s name.
Reading input from users in graphical applications is more complex, as blocking operations will cause the entire graphical interface to freeze. With a graphical application, you need to keep redrawing, processing events, updating elements, and refreshing the screen. If you stop doing this to wait for user input, then any dynamic visuals will stop!
Let’s see how to read input from the user using some example code. We can then talk through the different parts to understand how they come together to give you a dynamic application with user input.
In the above program we want to read in the user’s name and store it in the name variable. To get started with this we need to open a window and load a font to draw the text and input. There is also the standard event loop that repeats the basic actions of checking user input and drawing the screen until the program is closed.
The logic for reading input starts with the call to Start Reading Text. This tells SplashKit that you want it to collect text input by the user, and that you want it drawn into the passed-in Rectangle (in this case rect). SplashKit is now listening for input from, and collecting this text for you when you call Process Events.
SplashKit will continue reading text from the user until they hit the Escape or Enter key. You can check if text is still being read by calling the Reading Text function. In this example, we use this to update the name. You can also end text input yourself using the End Reading Text function.
When the SplashKit is no longer reading text, you can use Text Entry Cancelled to check if the user cancelled (by hitting Escape) the input. To read the actual value entered, you call Text Input. This will return the value entered by the user. If they did cancel the input, then this will be an empty string.
The key with graphical input will be to keep updating the data associated with the graphical elements. This will keep the screen updating as you collect the input from the user. For this, you need to Start Reading Text, then at some point collect the Text Input and End Reading Text.