Burnie Burnie - 2 months ago 16
C Question

Passing in arguments in C

How could I do something like this? I'm making a Sockets program that connects one program with another program via a port number. I want to pass in a command of

-p
that stands for port and then have a number after it to designate the port number. Example:
-p 9013
for Port 9013.

Here is what I have so far:

int main(int argc, char* argv[]) {
int i, portNumber;

for (i = 1; i < (argc - 1); i++) {
if (strcmp("-p", argv[i]) == 0) {
// add whatever comes after -p and declare portNumber as that integer
}
}
}


Any clue how I can maybe start this?

Answer
if (strcmp("-p", argv[i]) == 0) {
    portNumber = atoi(argv[i+1]) // Might want to check argv[i+1] exists in case the last command line parameter is "-p"
}