开发者

C++: how to switch through arguments?

So I have code like

 int main(int argc, char* argv[])
{ 
    string outputUrl ;
    string outputContainer ;
    string outputUserName ;

    for(int i = 0 i>=argc; i+2){
        switch(argv[i]){ //C2450
            case "-server" : {outputUrl += (argv[i+1]);} break; //C2051
            case "-container" : {outputContainer = (argv[i+1]);} break; //C2051
            case "-nickname" : {outputUserName += (argv[i+1]);}开发者_开发技巧 break; //C2051
    }
}

Why does it give me compiler error C2450 and on next line C2051? How to fix such thing?


The switch statement can't use strings. You'll need to replace it with a string of if-else if statements instead.


C and C++ switch statements only operate on integral types. You can do some stuff like casting the pointer to an int (and in fact you are switching on pointers), but you're still not going to get 'switching on strings' behavior like you want here.

Why no switch on pointers?


You can switch on numbers, not on pointers to strings. I take it you're transitioning from another language?

Also, i+2 should be i+=2.

Also, i>=argc should be i < argc


You can't switch on strings, only integer types. You will have to explicitly if/else each one. Secondly, break occurs inside the case statement, not outside.


You can't switch on a string, or anything else that isn't an integer or can't be converted to one. Use three "if" statements instead.


Use something like getopt. There is a nice (but not complete) implementation: http://www.codeproject.com/KB/cpp/xgetopt.aspx?msg=614581. Or use boost.Program_options: http://www.boost.org/doc/libs/1_41_0/doc/html/index.html.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜