how to populate a structure in command line arguments
so,
have to access the structure elements in mainCode:struct { --- --- } int main(int argc,char**argv) { return(struct) }
how to populate a structure in command line arguments
so,
have to access the structure elements in mainCode:struct { --- --- } int main(int argc,char**argv) { return(struct) }
I think this may be what you're trying to do. This is quick and dirty, it doesn't check for number or type of arguments. After compiling, you pass the arguments into the program like this when you execute it: ./program 21 benjamin
Code:#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc,char**argv) { int age = atoi(argv[1]); char name[20]; char *tempptr = argv[2]; strcpy(name,tempptr); printf("age: %i \n",age); printf("name: %s \n",name); // NOW GO AHEAD AND CREATE A STRUCT AS YOU USUALLY WOULD return 0; }
It's rather difficult to know what you want to achieve.
Command line arguments usually need to be checked, except in a beginner environment of teaching and learning code. There might be too many or too few, they might not be valid numbers in places which demand a number, if they are valid numbers, the numbers may be out of range.
If you are doing anything at all advanced, there are usually optional arguments.
If you go onto my website, and look at the "options parser" you will see how to write something which will do all this robustly. However it's almost certainly too advanced for what you want just now.
Lets say we have
and we want to populate that structure from a commandline argument consisting of name, number and salary. let's also say that name is a surname, and we know there will be no errors. Simply call strcpy() to duplicate the string and get the surname, atoi() to get the payroll, and atof() to get the float. The strings are in argv[1]. argv[2], and argv[3]. (argv[0] is the name of the program).Code:struct { char name[64]; int payrollno; float salary; } EMPLOYEE;
I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
Visit my website for lots of associated C programming resources.
https://github.com/MalcolmMcLean