1

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
The Rationalist
  • 743
  • 1
  • 10
  • 23
  • 1
    In the first example, `main` is run, and then it waits for people to type in input. In the second example, the OS runs `main` and passes it three parameters, `"w"`, `"h"`, and `"filename"`; – Mooing Duck Jan 16 '13 at 17:34
  • If you have to give it via STDIN, you could always use something like `echo 128 128 output.ppm | prog` – Mr. Llama Jan 16 '13 at 17:52

3 Answers3

4

Your program needs to parse command line parameters. Looking at the specification, the expected workflow is

>prog 128 128 output.ppm
//hit enter after the parameters

Look here to learn more.

Community
  • 1
  • 1
Csq
  • 5,775
  • 6
  • 26
  • 39
3

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.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
2

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.

andre
  • 7,018
  • 4
  • 43
  • 75