本文介绍了难道我理解的getopt()是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图扫描特定的字母,符号和价值观的命令行。我想扫描 - W,一个数字,而 - 的。我在我的最后一个问题的回应,我被告知要使用 getopt的()和谷歌搜索一点点之后,我想我可能会得到它,但我不当然。

这是我认为我做的:

  INT C = 0;
INT B =的argv [2];而((c = getopt的(ARGC,ARGV,-w,-s,B))

我想我扫描 ARGC - W - 的的argv [2] 值(即数)。但我不知道我是否正确地使用它吗?


解决方案

  INT数= 0;
INT SFlag的= 0;
INT选择;而((选择= getopt的(ARGC,ARGV,W:秒!))= - 1)
{
    开关(OPT)
    {
    案件的:
        SFlag的= 1;
        打破;
    案W:
        数=的atoi(OPTARG);
        打破;
    默认:
        / *报告的使用和退出? * /
        打破;
    }
}

上的数字转换是懒惰;你可以做更多更仔细的工作调用,调用与strtol(),比如一个函数。您可能需要有你类似设置为 SFlag的变量 WFLAG 变量,这样就可以区分 0 -w

在命令行上没有指定 -w 选项

I'm trying to scan the command line for certain letters, symbols and values. I want to scan for "-w", a number, and "-s". I got a response in my last question, I was told to use getopt() and after a little bit of Googling, I think I might get it, but I'm not sure.

This is what I think I'm doing:

int c = 0;
int b = argv[2];

while((c = getopt(argc, argv, "-w", "-s", b))

I think I'm scanning argc for "-w", "-s" and the argv[2] value (which is the number). But I do not know if I am using it correctly?

解决方案
int number = 0;
int sflag = 0;
int opt;

while ((opt = getopt(argc, argv, "w:s")) != -1)
{
    switch (opt)
    {
    case 's':
        sflag = 1;
        break;
    case 'w':
        number = atoi(optarg);
        break;
    default:
        /* Report usage and exit? */
        break;
    }
}

The conversion on the number is lazy; you can do more a more careful job calling a function that calls strtol(), for instance. You might need to have a wflag variable that you set analogously to the sflag variable so that you can distinguish -w 0 from 'no -w option specified on the command line'.

这篇关于难道我理解的getopt()是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 09:43