「-t text」や「-i 44」のようなオプションが好きです。私は "-fname"や "--very-long-argument = some_value"が好きではありません。
" - ?"、 "-h"、 "/ h"はすべてヘルプ画面です。ここで
は私のコードがどのように見えるかです:
int main (int argc, char *argv[])
{ int i;
char *Arg;
int ParamX, ParamY;
char *Text, *Primary;
// Initialize...
ParamX = 1;
ParamY = 0;
Text = NULL;
Primary = NULL;
// For each argument...
for (i = 0; i < argc; i++)
{
// Get the next argument and see what it is
Arg = argv[i];
switch (Arg[0])
{
case '-':
case '/':
// It's an argument; which one?
switch (Arg[1])
{
case '?':
case 'h':
case 'H':
// A cry for help
printf ("Usage: whatever...\n\n");
return (0);
break;
case 't':
case 'T':
// Param T requires a value; is it there?
i++;
if (i >= argc)
{
printf ("Error: missing value after '%s'.\n\n", Arg);
return (1);
}
// Just remember this
Text = Arg;
break;
case 'x':
case 'X':
// Param X requires a value; is it there?
i++;
if (i >= argc)
{
printf ("Error: missing value after '%s'.\n\n", Arg);
return (1);
}
// The value is there; get it and convert it to an int (1..10)
Arg = argv[i];
ParamX = atoi (Arg);
if ((ParamX == 0) || (ParamX > 10))
{
printf ("Error: invalid value for '%s'; must be between 1 and 10.\n\n", Arg);
return (1);
}
break;
case 'y':
case 'Y':
// Param Y doesn't expect a value after it
ParamY = 1;
break;
default:
// Unexpected argument
printf ("Error: unexpected parameter '%s'; type 'command -?' for help.\n\n", Arg);
return (1);
break;
}
break;
default:
// It's not a switch that begins with '-' or '/', so it's the primary option
Primary = Arg;
break;
}
}
// Done
return (0);
}
質問には、デザインパターンと提案が必要なので、これは「言語にとらわれない」とタグ付けする必要があります。 – martinatime