Friday, October 11, 2013

Simple Console Application in D

D is looking like the next big thing. Let's write a simple console application to become familiar with it.
Our program will ask the user for their name, and then greet the user. To work with input and output we will first import two libraries
import std.stdio, std.cstream;
Now for the main loop that will contain all our code.
void main(string[] args)
{

}
string[] args will contain any parameters passed from the command line. We won't need it for our program.

We will need a variable to store the name of the user so let's declare it.
char[] userName;
char[] is a character array or in other words a string. Notice that we have to put the brackets after the type and not after the variable name like in many other languages.

Now we'll output a message. Kind of looks like Pascal.
writeln("What is your name?");
This is the important part. We will take whatever the user enters and store it in our variable userName after the user presses Enter.
userName = din.readLine;
Finally we will greet the user and wait until the Enter key is pressed.
writeln("Hello " , userName);

din.getc();

Our final program:
import std.stdio, std.cstream;

void main(string[] args)
{
	char[] userName;
	
	writeln("What is your name?");
	userName = din.readLine;
	writeln("Hello " , userName);
	// Lets the user press <Return> before program stops
	din.getc();
}

No comments:

Post a Comment