Command line parameters c++ [duplicate]

2020-02-16 04:43发布

问题:

I have been asked to create a c++ program that "accepts a command line parameter and outputs the number of prime numbers less than this value; if no parameter is given, output just std::endl to std::cout"

I understand how to look up prime numbers but I am unsure what a "command line parameter" is and how it ties into the work. Also, I think if there is no parameter given, you just std::cout << std::endl?

I have tried to work out what a command line parameter is but cannot find any meaningful resources to this effect.

回答1:

Command line arguments are arguments passed to your program with its name. For example, the UNIX program cp (copies two files) has the following command line arguments:

cp SOURCE DEST

You can access the command line arguments with argc and argv:

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

argc is the number of arguments, including the program name, and argv is the array of strings containing the arguments. argv[0] is the program name, and argv[argc] is guaranteed to be a NULL pointer.

So the cp program can be implemented as such:

int main(int argc, char *argv[])
{
    char *src = argv[1];
    char *dest = argv[2];

    cpy(dest, src);
}

They do not have to be named argc and argv; they can have any name you want, though traditionally they are called that.