簡體   English   中英

使用命令行界面減少程序的代碼?

[英]Reduce code for program with command line interface?

我希望我的程序有一個如下所示的界面:

gen_data [start] [stop] [step]

[start][stop][step]是可選的,默認設置為-3*PI/23*PI/20.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; 
}

正如您所看到的,所有三個變量startstopstep每次都被分配 - 這不是多余的嗎? 我大致在想這樣的事情:

  • 如果 argc = 1:將所有 3 設置為默認值
  • if argc = 2: 僅將start設置為命令行 arg
  • if argc = 3:僅將startstop設置為命令行 args
  • 如果 argc = 4:設置startstopstep到命令行 args

我使用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 */

注意:除非在微控制器上,否則建議使用doublestrtod()而不是float

這樣,如果給出足夠的 arguments,您可以選擇設置stopstep ,如果沒有,您將使用默認值。

在實踐中避免使用atoi()atof() ,它們提供零錯誤檢測,並且在發生故障時不提供任何指示。 atof()將愉快地接受atof("my cow"); 並且在你不知道的情況下默默地返回0

如果您還有其他問題,請仔細查看並告訴我。

您可以先為所有變量設置默認值。 然后不根據argc的相等性設置它們,而是通過>例如

#include <stdlib.h>
#include <stdio.h>

int main (int argc, char **argv)
{
    float start = -(3*PI)/2;
    float stop (3*PI)/2;
    float step = 0.01;
    
    printf ("# gnuplot data\n"  
            "# x sin(x) cos(x)\n");
            
    if (argc > 1)
        start = atof (argv[1]);
    if (argc > 2)
        stop = atof (argv[2]);
    if (argc > 3)
        step = atof (argv[3]);

    for (float i = start; i <= stop; i += step)
        printf ("%6f\t%6f\t%6f\n", i, sin (i), cos (i));
    return 0; 
}

如前所述, floatatof的使用還有很多不足之處,但這是另一個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM