简体   繁体   中英

Passing parameters to a function from the Bash command line

I am running a C++ program from the command line on Bash, which is in a Linux environment. I am curious how you pass in a parameter from the command line. Here is my program:

#include <iostream>
using namespace std;

int large_pow2( int n );

int main()
{
   int value = 15;
   int largest_power = large_pow2(value);

   cout << "The highest power of 2 in " << value << " is " << large_power << "." << endl;

   return 0;
} 

int large_pow2( int n )
{
   int i = n
   int j = i & (i - 1);
   while( j != 0)
   {
      i = j;
      j = i & (i - 1);
   }
   return j;
}

After I compile the program I want to be able to use the command line to pass in a number to use for value . For instance, to run the program you type ./"program_name" where "program_name" is the name of my program without quotes. Is there a way to set value = n or something? When I run the program let's say I want n to be 20 so on the command line I type something like ./"program_name" 20 . Then the program would run with n = 20 . Is there a way to do that? I am completely new to a Linux environment and Bash so don't quite know how to do things in it yet.

Use argc and argv in int main(int argc, char *argv[]) and modify your code accordingly.

The argc arguments tracks the number of arguments passed to your program from CLI and is always >=1. When 1 it is it name of program. So argc[0] is program name.

argv holds the command line arguments, other than program name and is always char string. Hence we need to use appropriate converter like atoi , if you don't want string.

So your code will look like, error checking not done for simplicity

int main(int argc, char *argv[])
{
    //Now we expect argc ==2, program value, This will when argc != 2
    // We should use if in real scenario
    assert(argc == 2);
    int value = atoi(argv[1])
    int largest_power = large_pow2(value);

    cout << "The highest power of 2 in " << value << " is " << large_power << "." << endl;

    return 0;
} 

Your main method can take (int argc, char** argv) which are the count of arguments and the NUL terminated args. The program path is argv[0] so atoi(argv[1]) is probably what you want. Check argc ==2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM