-7

I write a program in C++, and the complier is G++

Now in the terminal, if I type ./main and enter it will run.

Yet I want to add something like a flag: ./main -apple or ./main -orange

apple and orange are two different methods to calculate one same problem. How do I make it?

I mean, when we do linux stuff, we usually can type dash sth, how does this work and what should I do in my program?

Any example or link?

Thanks in advance!

Euler
  • 335
  • 2
  • 5
  • 14
  • 2
    Vote to reopen: This is about using passing arguments to the `main` function and how to acess them. Not broad at all. – Thomas Matthews Apr 29 '14 at 16:43
  • True Thomas, though it's a bit unclear. OP: are you having trouble passing and receiving arguments in C++, or trouble with G++ compiler as you don't know how to pass them? I don't find this question broad, I find it unclear on what you are asking, on top of not providing code for what have you tried to solve the problem (like googling as Salgar pointed out) and why didn't it worked for you. – Nunser Apr 29 '14 at 17:20

1 Answers1

4
int main(int argc, const char* argv[]) {
    for(int i = 0; i < argc; ++i) {
        // argv[i] contains your argument(s)
    }
}

Some more details:

Accepting arguments passed to your program can be done by adding two arguments to main: One int, which is assigned the number of arguments you give to your program, and one const char* [], which is an array of C strings.

One example: Say you have a program main which should react to the arguments apple and orange. A call could look like this: ./main apple orange. argc will be 3 (counting "main", "apple", and "orange"), and iterating through the array will yield the 3 strings.

// executed from terminal via "./main apple orange"
#include <string>
int main(int argc, const char* argv[]) {
    // argc will be 3
    // so the loop iterates 3 times
    for(int i = 0; i < argc; ++i) {

        if(std::string(argc[i]) == "apple") {
            // on second iteration argc[i] is "apple" 
            eatApple();
        }

        else if(std::string(argc[i]) == "orange") {
            // on third iteration argc[i] is "orange" 
            squeezeOrange();
        }

        else { 
            // on first iteration argc[i] (which is then argc[0]) will contain "main"
            // so do nothing
        }
    }
}

This way you can perform tasks according to the application arguments, if you only want to squeeze an orange, just give one argument, like ./main orange.

Appleshell
  • 7,088
  • 6
  • 47
  • 96