Command Line Arguments

Command Line Arguments allow the user to run the program thruogh the terminal as well as pass in arguments into your program in one line. Most common use of command line arguments, are to pass in “strings” that represent file names from which you are going to read data from.

Format of Command Line Arguments

This is how you would write a simple program without command line arguments.

#include  
using namespace std;  

double square(int number) {
     return number*number; }  

int main() {
     int number;
     cin >> number;
     cout << square(number) << endl;
     return 0;
}

To run this program you’d do the following in the terminal. ($ denotes your input)

$./a.out
$10        //Your input
 100      //The output

Using Command Line Arguments

This is how you would use command line arguments.

#include 
 using namespace std;  

double square(int number) {
     return number*number; }  

int main(int argc, char* argv[]) {
      int number = atoi(argv[1]);      //Convert our c-string to int using the atoi function
      cout << square(number) << endl;
      return 0;
} 

To run this, you’d simply do the following in the terminal.

$./a.out 10 //One line in the terminal
100 //Output

How does command line arguments work?

int main(int argc, char* argv[])

The int argc parameter denotes the number of arguments passed in.
The char* argv[] parameter denotes a char pointer to a c-string.

So, typing the following:

$./a.out 10 45

Would produce the following:

In other words, the arguments are passed in as c-strings reason for why we converted our c-string to an int using the atoi function.

Things to do with Command Line Arguments

You may pass in any type of arguments. Try the following challenges to learn more.
Challenge 1: Create a program using command line arguments where you pass in your name, and two numbers, adds the numbers together and displays them both in the terminal.
Challenge 2: Create a program that accepts one int and returns the square of the number as shown above. The difference is that you need to error check your program. In other words, if they don’t pass in an int value or more than one int value, you should terminate the program. Hint: Use argc, and if statements.

Need more help? Go ask in the forums where our committed community will surely answer all your questions!


Related Posts

1 Star2 Stars (No Ratings Yet)

No comments yet... Be the first to leave a reply!

blog comments powered by Disqus