【发布时间】:2017-08-28 13:38:03
【问题描述】:
我知道已经有一些关于在 c 中解析命令行参数的其他问题和答案,但我希望有人能告诉我为什么我的代码不起作用。这是我的代码。我想解析我的论点,而不需要像 getopt.h /(unistd.h) 或 args.h
这样的外部头文件#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void showUsage(char *prog) {
printf("Usage for %s...", prog);
}
int main(int argc, char *argv[]) {
if (argc == 1) {
showUsage(argv[0]);
return EXIT_FAILURE;
}
int c;
char *input, *output;
for (c = 0; c < argc; ++c) {
if (strcmp((char *)argv[c], "-i")) {
input = (char *)argv[c + 1];
}
if (strcmp((char *)argv[c], "-o")) {
output = (char *)argv[c + 1];
}
}
printf("\nInput %s Output: %s", input, output);
return EXIT_SUCCESS;
}
【问题讨论】:
-
你的问题是什么?你期望给定的输入会发生什么?你观察到了什么?
-
请创建MCVE
-
您应该从
c = 1开始,因为argv[0]是程序名称,而不是参数。 -
strcmp在字符串相等时返回0。 -
如果没有找到一个选项,你应该为你的变量提供有效的默认值。