c - 使用命令行界面减少程序的代码?
问题描述
我希望我的程序有一个如下所示的界面:
gen_data [start] [stop] [step]
,和是可选的,默认设置
[start]
为,和。我有以下代码:[stop]
[step]
-3*PI/2
3*PI/2
0.01
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define PI 3.14569
int main (int argc, char **argv)
{
float i, start, stop, step;
printf ("# gnuplot data\n"
"# x sin(x) cos(x)\n");
switch (argc) {
case 1:
start = -(3*PI)/2;
stop = (3*PI)/2;
step = 0.01;
break;
case 2:
start = atof (argv[1]);
stop = (3*PI)/2;
step = 0.01;
break;
case 3:
start = atof (argv[1]);
stop = atof (argv[2]);
step = 0.01;
break;
case 4:
start = atof (argv[1]);
stop = atof (argv[2]);
step = atof (argv[3]);
break;
}
for (i = start; i <= stop; i += step)
printf ("%6f\t%6f\t%6f\n", i, sin (i), cos (i));
return 0;
}
正如您所看到的所有三个变量start
,stop
并且每次step
都被分配
- 这不是多余的吗?我大致在想这样的事情:
- 如果 argc = 1:将所有 3 设置为默认值
- if argc = 2: 只设置
start
为命令行 arg - if argc = 3: 只设置
start
和stop
到命令行参数 - if argc = 4: set
start
,stop
andstep
to 命令行参数
我使用switch
-的原因case
是为了能够利用失败 - 但无法让它发挥作用。有什么想法吗?代码是否正常?
解决方案
使用三元组真的很容易。你可以简单地做:
if (argc < 2) {
fputs ("error: insufficient arguments\n"
"usage: ./program start [stop] [step]\n", stderr);
return 1;
}
char *endptr;
float start = strtof (argv[1], &endptr), /* validation omitted */
stop = argc > 2 ? strtof (argv[2], &endptr) : -3*PI/2.,
step = argc > 3 ? strtof (argv[3], &endptr) : 3*PI/2.;
/* rest of code */
(注意:建议在微控制器上使用double
andstrtod()
而不是float
除非)
这样,您可以选择设置stop
,step
如果给出了足够的参数,如果没有,您将使用默认值。
避免使用atoi()
,atof()
在实践中,它们提供零错误检测,并且在发生故障时不提供任何指示。atof()
会很高兴地接受并在你不知道的情况下atof("my cow");
默默地失败返回。0
如果您还有其他问题,请仔细查看并告诉我。
推荐阅读
- python - pytesseract 和 opencv 读取文本的问题
- javascript - 我使用 Workbox CLI 及其 service-worker 生成器的 PWA 无法离线工作
- python - 预提交内置钩子的入口命令
- java - 带有 Viewholder 的 Android Recyclerview 更改宽度和高度 onClick
- javascript - 如何在 Next.js 中使用 stopPropagation()?
- parsing - 计算语法的 First 和 Follow
- javascript - 减速器/上下文 API
- python - 在由许多空格分隔的文件中搜索数字
- typescript - 为许多导入模式和智能感知编写打字稿
- reactjs - 无法从公用文件夹加载图像