Handling command line flags in C/C++

前端 未结 7 880
星月不相逢
星月不相逢 2020-12-14 21:03

I am looking for a very simple explanation/tutorial on what flags are. I understand that flags work indicate a command what to do. For example:

rm -Rf test
<         


        
7条回答
  •  感动是毒
    2020-12-14 21:39

    Actually you can write your own C++ programm which accepts commandline parameters like this:

    int main(int argc, char* argv[]){}

    The variable argc will contain the number of parameters, while the char* will contain the parameters itself.

    You can dispatch the parameters like this:

    for (int i = 1; i < argc; i++)
    {  
        if (i + 1 != argc)
        {
            if (strcmp(argv[i], "-filename") == 0) // This is your parameter name
            {                 
                char* filename = argv[i + 1];    // The next value in the array is your value
                i++;    // Move to the next flag
            }
        }
    }
    

提交回复
热议问题