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

Time:12-20

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 !!"

CodePudding user response:

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;
    }
}

CodePudding user response:

If you mean running from command line something like "test 123", then the argv[] argument contains your command line, when argv[0] is the name of the process, and argv[1] and so on are your command line arguments represented as strings

int main(int argc, char *argv[])
{
    int var = atoi(argv[1]);

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