D
Online D Compiler
main.d is compiled with LDC 1.43, the LLVM-based D compiler, and run with its output unbuffered, so a write() prompt shows before readln() waits for your input. The standard library, Phobos, is included.
Try it aboveHow D runs here
- Versions
- LDC 1.43
- Build
ldc2 -of=a.out main.d- Run
./a.out- Limits per run
- 768 MB memory, 15 s of CPU time on half a core, 2 MB of output
- Time
- Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
- Sandbox
- Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.
A D program that reads input
This main.d reads a line of numbers and works on it with Phobos ranges and UFCS, the call chain style D is known for:
import std.stdio; import std.string : strip; import std.conv : to; import std.algorithm : sort, sum, filter; import std.array : array, split; void main() { write("Numbers separated by spaces: "); auto nums = readln().strip.split.to!(int[]); writeln("Sum: ", nums.sum); writeln("Sorted: ", nums.dup.sort.array); writeln("Odd: ", nums.filter!(n => n % 2).array); }
$ ldc2 -of=a.out main.d && ./a.out Numbers separated by spaces: 12 7 30 5 8 Sum: 62 Sorted: [5, 7, 8, 12, 30] Odd: [7, 5]
Reading input in D
- readln() returns the line with its newline, so call strip on it before converting.
- readln().strip.to!int converts one number; .split.to!(int[]) converts a line of them.
- readf(" %d", &n) reads formatted input, with the leading space skipping whitespace.
Errors you’ll see
- “main.d(5): Error: undefined identifier `totl`” A typo or a missing import, with the line number.
- “std.conv.ConvException … Unexpected 'a' when converting from type string to type int” to!int got text that isn’t a number.
- Errors about a missing package: only Phobos is installed, not dub packages.
Questions
Which D compiler does this use?
LDC 1.43, the LLVM-based compiler, with Phobos.
How do I read input in D?
readln().strip for a line of text, readln().strip.to!int for a number. Type the input in the terminal while the program runs.
Can I use dub packages?
No. Only the standard library is available.