Read Command-Line Arguments: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Java example)
Line 44: Line 44:
forM_ (zip args [1..]) $ \(a,i) ->
forM_ (zip args [1..]) $ \(a,i) ->
putStrLn $ "Argument #" ++ show i ++ " is " ++ a
putStrLn $ "Argument #" ++ show i ++ " is " ++ a

=={{header|Java}}==
public class CmdLine{
public static void main(String[] args){
System.out.println("Number of args: " + args.length);
for(int i= 0;i < args.length;i++)
System.out.println("Argument #" + (i+1) + ": " + args[i]);
}
}


=={{header|Perl}}==
=={{header|Perl}}==

Revision as of 13:41, 3 December 2007

This page is a duplicate of another page. Its information should be merged with that of its sibling page. Please see the Talk page for details.
Task
Read Command-Line Arguments
You are encouraged to solve this task according to the task description, using any language you may know.

Read the command line arguments, display the total number, and display each one, including any reference to the program itself. (i.e., if the language includes the name and path of the executable as one of the arguments, include it.)

C

#include<stdio.h>

int main(int argc, char *argv[])
{
	int narg;

	printf("There are %d arguments\n", argc);
	for(narg=0; narg<argc; ++narg) 
		printf("Argument #%d is %s.\n", narg, argv[narg]);

	return 0;
}

C++

#include <iostream>
int main( int argc, char *argv[] )
{
     std::cout << "There are " << argc << " arguments." << std::endl;
     for (int argnum = 0; argnum < argc; ++argnum)
     {
          std::cout << "Argument #" << argnum << " is " << argv[argnum] << "." << std::endl;
     }

     return 0;  
}

Haskell

import System.Environment

main = do
  prog <- getProgName
  args <- getArgs
  putStrLn $ "Program name: " ++ prog
  putStrLn $ "There are " ++ show (length args) ++ " arguments:"
  forM_ (zip args [1..]) $ \(a,i) -> 
    putStrLn $ "Argument #" ++ show i ++ " is " ++ a

Java

public class CmdLine{
  public static void main(String[] args){
     System.out.println("Number of args: " + args.length);
     for(int i= 0;i < args.length;i++) 
        System.out.println("Argument #" + (i+1) + ": " + args[i]);
  }
}

Perl

#!/usr/bin/perl

print "There are $#ARGV arguments.\n";
foreach $argnum ( 0 .. $#ARGV )
{
        print "Argument $argnum is $ARGV[$argnum].\n";
}