在 C 中使用 if/else 语句的命令行参数

Command line arguments using if/else statements in C

我是编程新手,这个让我感到困惑。

我正在编写一个由 main 调用的函数,它接受命令行参数并将它们存储在 struct 中以备后用。这个具体示例用于图像编辑,但可以在任何地方使用。

期望的性能: 函数从命令行获取参数。识别并检查了三个特定参数:-h-o-t。如果存在,它们将改变 struct 值。参数 -o-t 将紧随其后的参数存储到各自的 struct 字段中。任何不是 -h 或前面没有 -o-t 的参数都被假定为输入文件名并存储在 flag->inputFile 中。如果考虑了所有参数,那么 flag->inputFile 应该保持 NULL 并且可以在主函数中进行测试,如果这是真的,程序将终止。

问题: 当没有指定输入文件时(使用上述参数) flag->inputFile 一直设置为 -o 当它被包含为一个参数。

解决方案: 多亏了 Scott,这个问题已经通过用 else if 替换几个 if 语句得到了回答,现在看来问题已解决,并且功能似乎按预期工作。 我对发生的事情的理解是 else 语句在 i 的每次迭代中都是 运行 除非包含 -t 参数,因为它是紧接在else

我使用的编译器是 gcc,这是我的代码。 (我知道我的结构没有打包,我仍在努力解决这个问题,但看不出它会如何导致我所看到的结果。分段错误,是的,但不是这个?)

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

struct PROMPTFLAGS {
    int help;    // Change from NULL if -h argument present
    char * outputFile;    // Store argument after -o as the output file
    char * inputFile;    // Argument not paired with a flag stored here as input file
    float threshold;    // Stores a value to use in image manipulation in main
};

struct PROMPTFLAGS * parsargs(int argc, char * argv[]) {
    struct PROMPTFLAGS* flag = malloc(sizeof(struct PROMPTFLAGS));
    int i;
    printf("argc: %d\n",argc);
    for (i = 1; i < argc; i++) {
        char * arg = argv[i];
        int str_aft = i+1;    // Allows the next string to be used in this iteration of the loop
        if (strcmp(arg,"-h") == 0) {
            flag->help = 1;
        }
        if (strcmp(arg,"-o") == 0) {    // Changing this to 'else if' seems to be a fix
            flag->outputFile = argv[str_aft];
            i++;        // Skips over next arg since already read by argv[str_aft]
        }
        if (strcmp(arg,"-t") == 0) {    // Changing this to 'else if' seems to be a fix
            flag->threshold = strtod(argv[str_aft],NULL);
            i++;        // Skips over next arg since already read by argv[str_aft]
        }
        else {
            flag->inputFile = arg;
        }
    }
    return flag;
}

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

    struct PROMPTFLAGS * flags;
    flags = parsargs(argc, argv);
    printf("Help = %d\n",flags.help);
    printf("Output = %s\n",flags.outputFile);
    printf("Input = %s\n",flags.inputFile);
    printf("Threshold = %s\n",flags.threshold);

return 0;
}

对于这个问题的第一个版本格式不佳,我深表歉意,希望这次编辑更好。我已经使函数的预期结果和我遇到的问题更清楚,并删除了我通过代码获得的大部分测试打印并添加了一些注释。我还包括了我的问题的解决方案(由另一个用户提供)以及我对损坏代码中发生的事情的理解。

如果人们仍然认为这是一个糟糕的问题或对其他人没有用,那么我很乐意将其删除,但已编辑并保留它希望它可以帮助其他人。

这是我第一次 post 关于堆栈溢出,我感谢大家在我学习编码和 post 问题时给予的帮助和耐心。

只要 arg 不是 "-t"(测试 "-t" 后的 else),您就可以设置 flag->inputFile = arg。我不确定您何时要分配给该字段,但我确定这不是正确的逻辑。例如,如果您想在 arg 是您要查找的其他特定标志的 none 时执行此操作,则应该使用 if ... else if ... else if ... else.