【发布时间】:2016-03-25 00:10:02
【问题描述】:
我想要做的是接受命令行参数并根据参数更改一些变量。我附上了我的一大段代码,因为整个代码大约有 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 这是一个字符串
程序应该打印:
"这将打印红色这是一个字符串"
如果用户输入:
./foobar -f 红色
程序应该打印“无效的命令行参数数量”。
最简单的方法是什么?我已经尝试了很多可能性,但没有运气。 不同数量的参数是我的主要问题(我也有超过 5 个选项,例如 -f -b -h -w -e)
帮助将不胜感激。如果你愿意,我可以添加我的整个代码。
【问题讨论】:
-
如果你没有将文本“这是一个字符串”放在双引号之间,程序会将每个单词解释为单个参数