2011-12-04 45 views
1

我想要做的是接受命令行参数并根据参数更改一些变量。我附加了一大段代码,因为整个代码大约是400行。在C中正确解析命令行参数

#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红色这是一个字符串

程序应该打印:

“这将打印红这是一个字符串“

如果用户输入:

./foobar -f红色

程序应打印 “无效号码的命令行参数”。

这样做最简单的方法是什么?我尝试了很多可能性,但没有运气。 不同数量的参数是我的主要问题(我也有超过5个选项,例如..- f -b -h -w -e)

帮助将不胜感激。如果你愿意,我可以添加我的整个代码。

+1

如果你不把文字“这是一个stri ng“之间,程序会将每个单词解释为单个参数 –

+0

查看#include http://www.crasseux.com/books/ctutorial/argp-example。html也http://stackoverflow.com/questions/7677562/whats-the-difference-between-argp-and-getopt –

回答

0

变化中断CA = 0为int CA = 1

由于的argv [0]是你的可执行

+0

对不起,我没有从我的c文件正确复制代码,现在检查它。谢谢。 –

5

通过这个链接,你会找到如何轻松做到全面支持命令行的描述名字参数:

http://www.gnu.org/s/hello/manual/libc/Getopt.html

+0

太棒了!非常感谢 ! –

+0

这不是一个好的答案。在这里添加一些信息+这个链接。请参阅[是否只包含其他链接的答案,真的是“好答案”?](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers/8259#8259) –

+0

好的,我明白了,编辑 – Nips

0

事情会变得更加清晰,如果你使用一个for循环,而不是傻“而其他”结构:

for(ca=1; ca < argc ; ca++) 
    { 
     if(!strcmp(argv[ca],"-f")) 
     { 
     printf("This works"); 
     ca++; /* need to test if ca can be incremented */ 
     if(!strcmp(argv[ca],"red")){ 
      printf("this will print red\n"); 
     } 
     else{ 
      printf("invalid color"); 
     } 
     } 
     else if(!strcmp(argv[ca],"")) 
     { 
     printf("invalid argument"); 
     } 
     else{ 
      strcat(somestring,argv[ca]); 
     } 
    } 
    printf("%s",somestring); 
1
char somestring[500]="";//need initialize 

    while(++ca<argc){//increment before condition test 
     if(strcmp(argv[ca],"-f")==0){ 

      if(ca < argc && strcmp(argv[ca],"red")==0){//need ca check 

     if(ca == argc){//bad strcmp(argv[ca],"") 
      printf("invalid argument");