Search code examples
c++constantscommand-line-argumentsbitsetvariable-types

How can I pass a constant int via command line argument in C++?


I want to be able to pass an integer via command line argument that I will call length. I need to make this constant, because it will be used to determine the size of several bitsets. I have tried doing this many ways, for example:

int main(int arc, const char* argv[]){
        const int * ptr;
        if (!(istringstream{argv[1]} >> ptr)) { return 1;}
        const int length = *ptr;

        bitset<length> right_ones = 1;
        return 0;
}

I also tried it this way:

int main(int arc, const char* argv[]){
        int test_int;   
        if (!(istringstream{argv[1]} >> test_int)) { return 1;}
        const int length = argv[1];

        bitset<length> right_ones = 1;
        return 0;
}

But none of the ways I have tried it worked. How can I accomplish this?


Solution

  • If it is going to be passed as a command line argument, then you cannot make it a constant.

    By the way, this is relevant to your case: Define bitset size at initialization?