如何处理 D 中没有命令行参数?
How to handle no command-line arguments in D?
D 中 main()
入口点的正确说法是
void main(char[][] args)
{
}
但是如果没有传递任何参数,我怎么知道它是一个数组?
void main(char[][] args)
在现代 D 中,规范签名为 void main(string[] args)
,如果您的程序不需要参数,则为 void main()
。
but how would I know if there aren't any arguments passed, given it's an array?
检查数组的 .length
属性。如果 args.length==1
,则没有参数传递给程序。 (参数 0 始终是程序本身,如 C/C++。)
使用string[]
:
void main(string[] args) {
// Check args.length
}
您还可以使用 std.getopt 进行进一步的解析。
朋友们已经说过,使用string[] args
:
import std.stdio;
int main(string[] args) {
if (args.length == 1) {
writeln("No arguments given. Aborting execution.");
return 1;
}
writeln(args);
return 42; // answer to everything
}
如果您的情况比较复杂,有很多参数,我建议您看一下 std.getopt 模块。
这是 std.getopt 文档中的示例:
import std.getopt;
string data = "file.dat";
int length = 24;
bool verbose;
enum Color { no, yes };
Color color;
void main(string[] args) {
auto helpInformation = getopt(
args,
"length", &length, // numeric
"file", &data, // string
"verbose", &verbose, // flag
"color", "Information about this color", &color); // enum
...
if (helpInformation.helpWanted) {
defaultGetoptPrinter("Some information about the program.",
helpInformation.options);
}
}
D 中 main()
入口点的正确说法是
void main(char[][] args)
{
}
但是如果没有传递任何参数,我怎么知道它是一个数组?
void main(char[][] args)
在现代 D 中,规范签名为 void main(string[] args)
,如果您的程序不需要参数,则为 void main()
。
but how would I know if there aren't any arguments passed, given it's an array?
检查数组的 .length
属性。如果 args.length==1
,则没有参数传递给程序。 (参数 0 始终是程序本身,如 C/C++。)
使用string[]
:
void main(string[] args) {
// Check args.length
}
您还可以使用 std.getopt 进行进一步的解析。
朋友们已经说过,使用string[] args
:
import std.stdio;
int main(string[] args) {
if (args.length == 1) {
writeln("No arguments given. Aborting execution.");
return 1;
}
writeln(args);
return 42; // answer to everything
}
如果您的情况比较复杂,有很多参数,我建议您看一下 std.getopt 模块。
这是 std.getopt 文档中的示例:
import std.getopt;
string data = "file.dat";
int length = 24;
bool verbose;
enum Color { no, yes };
Color color;
void main(string[] args) {
auto helpInformation = getopt(
args,
"length", &length, // numeric
"file", &data, // string
"verbose", &verbose, // flag
"color", "Information about this color", &color); // enum
...
if (helpInformation.helpWanted) {
defaultGetoptPrinter("Some information about the program.",
helpInformation.options);
}
}