In: Computer Science
How do I add additional command line arguments in C++? I am working on a programming assignment that has the user input a file into the command line and then they have the option to also add a series of other arguments to the command line. I know how to accept the text file from the command line by using:
int main(int argc, char *argv[]) { /.../ }
Then filename(argv[1]) would be the text file that they put into the command line. The part I am confused how to do is the additional command line arguments and the syntax on how to use it. It is asking to add:
-LL=t which The line length should be set to t. The value of t must be a positive integer greater than 0.Default value of t = 20.
-IN=n which The indentation should be set to n. The value of n must be a positive integer greater than 0.Default value of n =5.
and there are a few more which I should be able to do once I understand how to add this option to add to the command line. Not sure how to add these arguments so they'll be accepted to the command line or how to set their default values. Also, do the dashes '-' make a difference in handling the additional commands?
Would I have to add something like ", int -LL=t)* or something like that after argv[], where I declared the main function?
Hopefully that made sense and I appreciate any help to understand how to do this.
As far as I can understand your question, below are my take on this:
Pro tip: Try to look into this more simply. These command-line arguments can be very complex if handled in the wrong way.
Please look at the comments of the program for more clarity.
#include<bits/stdc++.h>
using namespace std;
int main(int argc, char** argv)
{
cout << "Total number of entered arguments: " << argc << "\n"; // argc will hold the number of command line arguments entered.
/*
Now for the default value which we want to have a default value
Lets us suppose a, we are running the program as
"multiple_command_line_arguments hey 1 -t a.txt".
Here, for the third argument we want to have a default value as 5
*/
int thirdValue = 5; // Setting the default value
for (int i = 0; i < argc; ++i) // Now here, we are looping through the entire given arguments.
{
// Our given arguments will start from index-1 and will go till index (argc-1)
if(i==2 && argv[i]>0) // argv[0] will have the name of the file
cout << thirdValue << "\n";
else
cout << argv[i] << "\n";
}
return 0;
}
Sample Input-Output/Code-run:
Input: multiple_command_line_arguments hey 1 -t a.txt
Input: multiple_command_line_arguments hey 10 -t a.txt
Please let me know in the comments in case of any confusion. Also, please upvote if you like.