argc, argv[]

closed account (DEUX92yv)
I'm just curious about this. Is it possible to use int argc, char* argv[] as the parameters for multiple functions? Say, an int main(int argc, char* argv[]) and a function called inside of main (using different names for the arguments), like int func(int argc2, char* argv2[])? What would be required to do something like this?
You can easily pass the program arguments to other functions:

1
2
3
4
5
6
7

void f(int argc, char **argv) { /***/ }

int main(int argc, char **argv) {
    f(argc, argv);
}
As R0mai says, yes, you can. argc and argv are just function parameters like any other, and you can treat them as such in your code.
Last edited on
closed account (DEUX92yv)
I guess what I mean is can you do something like this:
1
2
3
4
5
6
7
8
9
10
11
int main(int argc, char *argv[])
{
   // Declare and initialize a char* array
   char *argv2[] = /* something*/;
   f(argc2, argv2[]);
}

void f(int argc2, char *argv2[])
{
   // Do stuff using a switch statement based on argc2
}


My problem is that I'm writing a program that must take in two arguments (program name and an input file name) then take in another input of one to five arguments, then do different things based on how many arguments are taken in here. If I can do this without writing a separate function that's fine too - I just don't know how to do it.
do you mean that the extra 1-5 arguments are read from the file? if so, just do this to get them:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream>
using namespace std;

int main (int argc, char *argv[])
{
    if (argc!=2)
    {
        cout << "Incorrect arguments\n";
        return 0;
    }
    ifstream in (argv[1]);
    // Read arguments from in and do something with them here
}
Topic archived. No new replies allowed.