Search code examples
c++functioncmdparameters

How to use parameters from commandline inside a main function in C++ using SET-Command


Sorry, I have never really worked with Commandline parameters. Maybe this is a stupid question:

I have a simple file test.cpp with a main function. I now want to start this program from the Commandline after having set the variable var with a value from the Commandline. (How) Can I do this?

test.cpp:

int main(int argc, char *argv[])
{
  int var;  // do I need to declare this variable here?

  if (var == 123)
      puts(" var=123 !!");      
}

In the Commandline can I type something like that:

  • set /A var=123
  • test

And main would print "var=123 !!"


Solution

  • set defines an environment variable. That's a variable that exists in the environment of your application, i.e. outside your application. You can't use that to set variables inside your program.

    You can however access the environment using std::getenv.

    #include <iostream>
    #include <cstdlib>
    int main(void) {
        const char* env_abc = std::getenv("ABC");
        if (env_abc)
        {
            int abc = std::atoi(env_abc);
            std::cout << abc;
        }
    }