Thread: Filling an array from the Command line

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    2

    Question Filling an array from the Command line

    Ok.. I know how to fill an array, but how does one go about filling an array from command line? Like c:\program1.exe 2.0 1.3 2.2
    using floats as my example. Thank you for any help in advance.

  2. #2
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    declare your main function like this:

    int main(int argc, char **argv)

    int argc contains the number of arguments you passed to your command line including the program name.

    char argv is an array of char arrays. Each one will contain the float you passed to it.

    You can simply declare a fixed size array and traverse through argv to read in your floats. Remember that it's a string and you will need to convert it to a float by using atof(). You can also make it more advanced by reading in argc and dynamically creating your array during runtime.

    EDIT - must...fix.....grammar
    Last edited by Cshot; 09-26-2002 at 01:53 PM.
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  3. #3
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Code:
    # include <stdio.h>
    # include <stdlib.h>
    
    
    int main (int argc,char** argv)
    {
    	int i;
    	float *f;
    
    	if(argc<=1){
    		printf("No Params!");
    		return 1;
    	}
    
    	f = malloc(sizeof(float)*argc-1);
    	if(!f)return 1;
    
    	for(i=0;i<argc-1;i++)
    		f[i] = (float)atof(argv[1+i]);
    
    	for(i=0;i<argc-1;i++)
    		printf("Float found! - %2.2f\n",f[i]);
    
    	free(f);
    
       
        return 0;
    }
    CShot beat me...but here's some code anyway

  4. #4
    Registered User
    Join Date
    Sep 2002
    Posts
    2
    Thank you both so very much!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. filling an array of structures?
    By voodoo3182 in forum C Programming
    Replies: 9
    Last Post: 08-06-2005, 05:29 PM
  2. [question]Analyzing data in a two-dimensional array
    By burbose in forum C Programming
    Replies: 2
    Last Post: 06-13-2005, 07:31 AM
  3. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  4. Filling a 2d Array cause program to crash
    By Geo-Fry in forum C++ Programming
    Replies: 2
    Last Post: 05-22-2003, 07:00 AM
  5. filling an array
    By Flex in forum C Programming
    Replies: 7
    Last Post: 02-28-2002, 03:11 PM