c - 不知道如何检查 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++
或Python
。该==
运算符不适用于比较字符串。做什么,不是你打算做什么。它改为比较两个指针。
为此,您应使用strcmp
函数族。
if(strcmp(flag, "-f") == 0){
/* equals */
}
if(strncmp(flag, "-f", 2) == 0){
/* equals */
}
推荐阅读
- python - 无法导入 python 模块。安装了 pip3 和 python 3.5 和 python3.7
- javascript - 如何通过 Javascript 中的唯一属性对数组中的对象进行分组?
- django - 在 django 中编辑表单集
- sql - CTE进入无限循环?
- amazon-web-services - java 名为“corretto8”的未知运行时版本。此构建映像具有以下版本:openjdk11、openjdk8
- c# - 如何使用 EF Core 和 .Net Core 3.1 使用 Mac 设置 SQL Server 的连接字符串
- ios - node.js - 第一个参数必须是字符串类型或带有 http 模块的 Buffer 实例
- php - Yii 1.1 如何从 queryBuilder 获取原始查询
- sql - 如何禁用 bash 信息打印
- php - php preg_match 带通配符