Recently in a couple class projects I have needed to use command line arguments, and the first time dealing with these can be a little confusing. So here is four short programs that simply output these arguments.
What I mean by this is that I need to accept a string while I am calling the program name. For example I am running my program called printString and I want it to display the text hello. So I run it like so
./printString.c hello
This would make my program print hello. Now I will show how its done. Its basically just like passing parameters to a normal function, except its a character string, and there is no limit to how many you can add, note that these examples are only for 1 parameter. A simple loop would allow you to output them all.
Also For the c and c++ example the argc variable is how many parameters you passed in. The reason I use 1(one) and not 0 is because arg[0] is the name of the file itself.
In Java
public class printString{
public static void main (String[] args) {
System.out.println(args[0])
}
}
In c
nt main(int argc, char **argv)
{
strcpy(ip_addr_dot, argv[1]);
printf(" %s", ip_addr_dot);
return 0;
}
In c++
#include<iostream>
using namespace std;
int main(int argc, char **argv)
{
cout << argv[1];
return 0;
}
In Python
import sys for arg in sys.argv: print arg
Note the there is an indent in front of print.
All of these short programs output the word hello and then end.