Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Don';我不知道如何在C中检查输入参数_C - Fatal编程技术网

Don';我不知道如何在C中检查输入参数

Don';我不知道如何在C中检查输入参数,c,C,我想检查我的C程序的第二个输入参数是-f还是-p。我使用if语句来检查这一点,由于某种原因,它无法将参数识别为字符串,但当我打印参数时,它看起来是相同的。我尝试了两种方法,第一种是将参数复制到字符数组,第二种是直接检查参数。我错过了什么 #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> int main(int argc, char *arg

我想检查我的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);
    }
}
    
#包括
#包括
#包括
#包括
int main(int argc,char*argv[])
{
字符标志[3]=“”;
memcpy(flag,argv[1],3);
printf(“%s\n”,标志);
//检查第二个参数是否为-f或-p
如果(标志==“-f”)
{
printf(“1”);
}
else if(argv[1]=“-p”)
{
printf(“2”);
}
其他的
{
fprintf(stderr,“错误:第二个参数%s必须是或”,argv[1]);
退出(退出失败);
}
}

C不是
C++
Python
=
运算符不用于比较字符串。它所做的,不是你想要它做的。而是比较两个指针

为此,您应使用strcmp函数系列

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

您应该使用
strcmp
来比较字符串。但是,在使用
strcmp
之前,必须确保字符串参数正确以null结尾。否则,
strcmp
将导致。因此,您可能需要考虑使用<代码> StncPyPys<代码>而不是<代码> MycPy。@ AndreasWenzel,您认为ARGV(1)是否会大于参数的最大缓冲区大小?我不认为main的编译器/系统引导程序中没有保护。我的意思是,编译器的明智行为是修剪和零终止命令行参数。@AndreasWenzel和thx for edit,我因教育不当而脸红。在访问
argv[1]
之前,您应该确保
argc>=2
。否则,
argv[1]==NULL
程序将崩溃。