c - 使用 main() 参数向量
问题描述
我正在尝试使用 main() 参数向量来获取三个选项,它会输出所有三个结果。为什么它不能工作?
#include <ctype.h>
#include <stdio.h>
void output_1(char *str);
void output_2(char *str);
void output_3(char *str);
int main(int argc,char *argv[])
{
char str[40];
gets(str);
if (argv[1]="-p")
{
output_1(str);
}
if (argv[1]="-u")
{
output_2(str);
}
if (argv[1]="-l")
{
output_3(str);
}
}
output_1/2/3 的定义无关紧要。
解决方案
C 字符串比较使用strcmp
.
这是有关如何测试命令行参数并确保解析可靠的代码示例(需要检查参数的数量)。然而,解析参数最好使用getopt
功能来完成。
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{
if (argc != 2)
{
printf("missing arguments");
return -1;
}
if (!strcmp(argv[1],"-p"))
{
printf("-p");
}
else
{
printf("unknwon arg %s",argv[1]);
}
}
推荐阅读
- kubernetes - prometheus pod 重启次数不是整数
- django - 如何在没有互联网的情况下为 Django 开发设置虚拟环境?
- python - Selenium page_source 被截断
- python - 如何在 python 中为 Windows 10 上的 TensorFlow 设置带有 CUDA 的 GPU?
- oracle - 来自数组的 Oracle PL/SQL 批量更新
- c++ - 打开包含变量名的文件
- linux - 在 linux shell 脚本参数中传递特殊字符
- jenkins - 在 groovy 中解析 xml 文件
- python - 仅在行尾删除连字符正则表达式 python r
- python - 即使安装了 selenium,导入 selenium 时也会出错