Jump to content

Passing variables into c++ using the command line

Go to solution Solved by Mira Yurizaki,

You pass in arguments like

./a.out 1 2 3 4 5

 

Arguments are space-separated terms that fill in the argv array. Argc is used to tell you how many arguments there are. Also, important note, the first entry in argv is always the command. In the example above, argv[0] is ./a.out. So you want to make sure you have at least 2 arguments before proceeding.

So I have this C++ code here and it compiles fine, but I was wondering how to pass in a variable for argv. Currently I'm running the code as such,  

"   g++ counter.cc #0 '21'   "

This compiles but it gets 0 as count. So what do I need to change? Ive tried using int count = atoi(&argv) and other similar variations but can't figure out where I'm going wrong with this.

On Linux btw if its relevant.


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[ ]){
    
    int count = atoi( argv[0]);
    printf("Count :%i \n", count);

    for(int i = 1; i <= count; i++){
        printf("Process: %d %i \n", getpid(), i );
    }
    return(count);
    perror("Return Failed");
    exit(EXIT_FAILURE);    
}

 

Link to post
Share on other sites

You pass in arguments like

./a.out 1 2 3 4 5

 

Arguments are space-separated terms that fill in the argv array. Argc is used to tell you how many arguments there are. Also, important note, the first entry in argv is always the command. In the example above, argv[0] is ./a.out. So you want to make sure you have at least 2 arguments before proceeding.

Link to post
Share on other sites

When the arguments you are receiving are relatively simple, then argc and argv should be fine, in a situation like this they are . However sometimes the arguments you want to receive will be more complex, the GNU C library (which can be used in C++ as well) has a header called argp, which is to help with parsing those longer arguments, an example of how to use it is here, however it is not directly a part of C++ so the syntax of argp is C-like, which can get complex and messy sometimes (but all code can get complex and messy).

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×