Read standard input
Use the readln()
function to read data from the standard input. It reads the whole line as a string:
To work with data types other than strings, you can convert the input using conversion functions like .toInt()
, .toLong()
, .toDouble()
, .toFloat()
, or .toBoolean()
. It is possible to read multiple inputs of different data types and store each input in a variable:
These conversion functions assume the user enters a valid representation of the target data type. For example, converting "hello" to an integer using .toInt()
would result in an exception as the function expects a number in the string input.
To read several input elements separated by a delimiter, use the .split()
function specifying the delimiter. The following code sample reads from the standard input, splits the input into a list of elements based on the delimiter, and converts each element of the list into a specific type:
Handle standard input safely
You can use the .toIntOrNull()
function to safely convert user input from a string to an integer. This function returns an integer if the conversion is successful. However, if the input is not a valid representation of an integer, it returns null
:
The readlnOrNull()
function is also helpful in safely handling the user input. The readlnOrNull()
function reads from the standard input and returns null if the end of the input is reached, whereas readln()
throws an exception in such a case.