Console Input
Kotlin’s standard library provides the function readln() to read a line
of input from the console. This line of input is returned as a String
object.
Here’s an example, with the equivalent C and Python code provided for comparison:
print("Enter your name: ")
val name = readln()
char name[80];
printf("Enter your name: ");
fgets(name, sizeof name, stdin);
name = input("Enter your name: ")
You can see that Python’s approach is the most concise and C’s the most verbose, with Kotlin somewhere in between.
Task 3.2
-
In the
tasks/task3_2subdirectory of your repository, create a small Kotlin program containing the two lines shown above.Add a third line that prints the length of the string supplied by the user. This is available to you as the
lengthproperty of the string variable, i.e.,name.length. -
Compile the program, then run it a few times, trying various lengths of input, including no input at all (just press the
Enterkey for this, without typing anything else). -
Now run the program and press
Ctrl+Dinstead of entering anything. What happens?