How to get data from standard input in D programming
Overview
Programs that tend to be interactive have to provide at least a single avenue for users to enter details and information as requested of them. To achieve it in the D programming language, there is a simple method, the readf() method.
What is the readf() method?
This is an built-in method in the D programing language, making it possible for input to be accepted by the D program code. In the readf() method, any data type can be accepted using the type formatter, a method parameter.
Syntax
readf(type_formatter, store_variable);
Parameters
type_formatter: A string used as a placeholder indicating the expected data type.store_variable: A variable of any data type that will hold the input value from the user.
Code
We should see a prompt asking for our pet’s age before entering the answer and sending it to display a typical standard input/output.
Note: Make sure to enter a value in the box “
Enter the input below.”
import std.stdio;void main() {write("What is the age of your pet? \n");/* The definition of the variable that will be used to* store the information that is read from the input. */int petAge;// Storing the input data to that variablereadf("%s", petAge);writeln("Your pet is ", petAge, " years old");}
Enter the input below
Explanation
- Line 1: We import the
stdiolibrary. - Line 2: We start the
mainwith a return type ofvoid. - Line 3: We write the prompt to input something to the output.
- Line 5: We define the variable used to store the information read from the input.
- Line 8: We have the read input line to get data from the user.
- Line 9: We write to display the data entered by the user.