首页 > 解决方案 > 不知道如何检查 C 中的输入参数

问题描述

我想检查我的 C 程序的第二个输入参数是 -f 还是 -p。我正在使用 if 语句来检查这一点,由于某种原因,它不能将参数识别为字符串,但是当我打印参数时,它看起来是相同的。我尝试了两种方法,第一种是将参数复制到字符数组,第二种是直接检查参数。我错过了什么?

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

int main(int argc, char *argv[])
{
    char flag[3] = "";
    memcpy(flag, argv[1],3);
    printf("%s\n", flag);

    // check that the second argument is either -f or -p
    if (flag == "-f")
    {
        printf("1");
    }
    else if (argv[1] == "-p")
    {
        printf("2");
    }
    else
    {
        fprintf(stderr, "ERROR: Second argument %s must be <-f> or <-p>\n", argv[1]);
        exit(EXIT_FAILURE);
    }
}
    

标签: c

解决方案


C 不是C++Python。该==运算符不适用于比较字符串。做什么,不是你打算做什么。它改为比较两个指针。

为此,您应使用strcmp函数族。

if(strcmp(flag, "-f") == 0){
 /* equals */
}
if(strncmp(flag, "-f", 2) == 0){
 /* equals */
}

推荐阅读