c - 在命令行中定义输入类型

标签 c linux

我正在C中进行某个项目。到目前为止,我所做的是从命令行读取参数,而不是返回最小或最大数。例如:

./find -m -M 1 3 4 5
The smallest number is: 1
The biggest number is 5


我想做的是添加标志“ t”(在切换情况下为“ t”),因此当我运行脚本时,可以在整数和浮点数之间进行选择。例如:

./find -m -t float 1.2 4.5 1.9 2.3
The smallest number is: 1.2


或与整数相同的东西。

谢谢你的帮助。

简短格式的代码:

int main(int argc, char *argv[]){
int array[30];

int x = 0;
while ((x = getopt(argc, argv, "htm")) != -1 )
{
    switch(x)
    {
    case 'h' :
        printf("Help.\n");
        break;
    case 't':
        break;
    case 'm' :
        for(int a = optind; a < argc; a++)
        {
            array[a] = atoi(argv[a]);
        }
        for (int i = optind; i < argc; i++)
        {
            for (int j = optind; j < argc - 1; j++)
            {
                if (array[j] > array[j + 1])
                {
                    int temp = arrray[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        printf("The smallest one: %d\n", array[optind]);
        break;
   }
}
return 0;
}

最佳答案

一个非常快速的解决方案可能是这样的:

int type = 0;

// parse the arguments
if (argc > 1){
    for (int i = 0; i < argc; i++){
        if (!(strcmp(argv[i],'-t')))
           if (!(strcmp(argv[i+1],'float')))
                type = 1; 
    }
}


然后检查类型是否为0,使用int或为1,使用float。
它不是很漂亮,您当然需要进行一些检查,而不是盲目地使用argv [i + 1],但是它很容易编写并且可以正常工作(因为我写得很快,所以可能有一些错别字)

附言我从没使用过getopt,但是它可能会容易得多,因为您不需要使用strcmp

另外,该开关只能在char上使用,因此要在字符串上使用它,则必须在string [0]上使用它,但是您将接受以“ i”或“ f”开头的每个字符串,而不仅是“ int”和“浮动”

关于c - 在命令行中定义输入类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40303457/

相关文章:

c - 为什么 'wait' 函数总是返回 -1?

python - Pygtk 选项卡中的 TreeView

python - 尝试安装 tensorflow 时收到奇怪的权限错误

linux - 使用 ./studio.sh 或任何 bash 脚本运行 android studio 时权限被拒绝

c - 每个线程都有唯一的信号量

c++ - libao在window下编译

c - == 用于指针比较

regex - 用于从变量中提取 UUID/PARTUUID 的 BASH 脚本

python - Python 中的多处理问题。 Windows 与 Linux

javascript - 如何在C中建立javascript和cgi之间的通信 channel ?