getopt usage help to stderr?
Salih Dincer
salihdb at hotmail.com
Wed Apr 9 01:23:01 UTC 2025
On Tuesday, 8 April 2025 at 20:14:56 UTC, Andy Valencia wrote:
>
> p.s. Ironically, I could probably have coded a getopt in less
> time than I've spent on std.getopt...
:)
Please try the following example with the parameters -h, -e, -l,
and -v in that order:
```d
import std.array : appender;
import std.getopt, std.stdio;
void main(string[] args)
{
enum errMsg = "\nPlease try again!";
string test;
bool verbose;
try
{
auto rslt = getopt(
args,
"exit|e", "Exit process", &test,
"verbose|v", "Enable verbose output", &verbose
);
if (rslt.helpWanted)
{
// Capture help text to a string
import std.array : appender;
import std.format : formattedWrite;
auto helpText = appender!string();
defaultGetoptFormatter(helpText, args[0],
rslt.options);
// Output to stderr
stderr.write(helpText.data);
return;
}
}
catch (Exception e)
{
stderr.writeln(e.msg, errMsg); // ... Please try again!
// Also output help on error
auto helpText = appender!string();
defaultGetoptFormatter(helpText, args[0],
getopt(args).options);
stderr.write(helpText.data);
return;
}
// Your program logic here
if (verbose)
writeln("Verbose Mode: on");
}
```
SDB at 79
More information about the Digitalmars-d-learn
mailing list