Reputation: 753
I have a C++ program that accepts three inputs: an integer for width, an integer for height, and a filename. Right now, I compile, and run the program like this (assuming I named it prog):
>prog
// hit enter
>128 128 output.ppm
This results in a successful output, but the program description says the proper command-line syntax is:
>prog w h filename
That's all it says. Does this imply that my program should be able to start on the same line? Perhaps it implicitly means you hit enter after typing the program name, but if not, is there a way to actually do this?
Upvotes: 1
Views: 142
Reputation: 110668
You're approaching the problem incorrectly. You are taking your input via std::cin
after your program has been started. Your program specification states that the input should be given as part of the command. Consider a command like ls -l
- the -l
is part of the command and is passed to the program to parse and act upon.
You need to allow a command like prog 128 128 output.ppm
to be run, so the user would type that and then press enter to run the program. How do you get access to the command line arguments within your C++ program? Well, that's what the argc
and argv
parameters of the main
function are for. Your main function should look like this:
int main(int argc, char* argv[]) { ... }
The argc
argument gives you the number of arguments passed in the command line (it will be 4, in the example given) which is also the size of the argv
array. Each element is an argument from the command. For example, argv[0]
will be "prog"
, argv[1]
will be "128"
, and so on. You need to parse these values and, depending on their values, change the functionality of your program.
Upvotes: 3
Reputation: 7249
You can pass command via the argument in the main function:
int main(int argc, char *argv[]) {
}
argc
is the number of arguments and argv
is an array of arguments.
Upvotes: 2