Roh*_*ukh 1 c command-line-arguments
我想要做的是接受命令行参数并根据参数更改一些变量.我附加了一大块代码,因为整个代码大约是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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果用户输入:
./foobar -f red这是一个字符串
程序应该打印:
"这将打印红色,这是一个字符串"
如果用户输入:
./foobar -f red
程序应该打印"无效的命令行参数".
最简单的方法是什么?我已经尝试了很多可能性而没有运气.不同参数的数量对我来说是主要的问题(我也有超过5个选项,例如-f -b -h -w -e)
帮助非常感谢.如果你愿意,我可以添加我的整个代码.