我想做的是接受命令行参数并根据参数更改一些变量。我附上了一大块代码,因为整个代码大约有 400 行。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char somestring[500];
int ca=0;
if (argc==1) //if no arguments are specified use defaults
{
}
else
{
while(ca<argc)
{
ca++
if(strcmp(argv[ca],"-f")==0)
{
printf("This works");
ca++;
if(strcmp(argv[ca],"red")==0){
printf("this will print red\n");
}
else{
printf("invalid color");
}
}
if(strcmp(argv[ca),"")==0)
{
printf("invalid argument");
}
else {
strcat(somestring,argv[ca]);
}
}
printf("%s",somestring);
}
}
如果用户输入:
./foobar -f red this is a string
程序应该打印:
"this will print red this is a string"
如果用户输入:
./foobar -f red
程序应该打印“命令行参数的数量无效”。
最简单的方法是什么?我已经尝试了很多可能性但没有运气。 不同数量的参数是我的主要问题(我还有超过 5 个选项,例如..-f -b -h -w -e)
帮助将不胜感激。如果你愿意,我可以添加我的整个代码。
最佳答案
正确的方法是使用许多现有的解析器库之一,而不是自己手动解析。它更简单、更强大,并且省去了重新发明轮子的麻烦。
GNU libc
手册建议了一些库,具体取决于您想要的花哨/标准:
http://www.gnu.org/software/libc/manual/html_node/Parsing-Program-Arguments.html
getopt
:如另一个答案所述argp
:我通常的选择子选项
:用于复杂的解决方案
关于c - 正确解析 C 中的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8374810/