How to read a single character in D language?

BoQsc vaidas.boqsc at gmail.com
Fri Nov 19 20:51:09 UTC 2021


On Friday, 19 November 2021 at 18:01:57 UTC, Adam D Ruppe wrote:
> On Friday, 19 November 2021 at 17:36:55 UTC, BoQsc wrote:
>> Let's say I want to write a simple program that asks for an 
>> input of a single character.
>> After pressing a single key on a keyboard, the character is 
>> printed out and the program  should stop.
>
> This is platform specific. About 10 lines of code for a minimum 
> implementation per OS, but if you don't wanna do it that way my 
> library has a function for it with a prepackaged sample:
>
> http://arsd-official.dpldocs.info/arsd.terminal.html#single-key
>
> that's arsd-official:terminal on dub or you can grab the file 
> from my github repo.
>
> I guess you could view my source to see the impl but I don't 
> feel like pulling it out right now.

Thanks Adam.
I've tested and it does work on Windows 10.

> mkdir "read_character_project"
> cd "read_character_project"
> dub init
> dub add arsd-official:terminal
> notepad ./source/app.d

import arsd.terminal;

void main() {
	auto terminal = Terminal(ConsoleOutputType.linear);
	auto input = RealTimeConsoleInput(&terminal, 
ConsoleInputFlags.raw);

	terminal.writeln("Press any key to continue...");
	auto ch = input.getch();
	terminal.writeln("You pressed ", ch);
}


> dub run

Performing "debug" build using C:\Program Files\LDC 
1.28\bin\ldc2.exe for x86_64.
arsd-official:terminal 10.3.10: target for configuration "normal" 
is up to date.
arsd ~master: target for configuration "application" is up to 
date.
To force a rebuild of up-to-date targets, run again with --force.
Running arsd.exe
Press any key to continue...
You pressed u

___

Of interest, I also tried to look up getch() inside
http://arsd-official.dpldocs.info/source/arsd.terminal.d.html#L2867

But the source file overwhelmed me by its size.

For now I'm still interested in a more simple standalone 
implementation that would be more learning friendly, or at least 
with little explanation of basic things behind the code and how 
it is interfacing with the operating system, the native library.



More information about the Digitalmars-d-learn mailing list