Gistrec icon

Understanding argc & argv [taking in command line arguments]

Gistrec | PRO | 04/08/18 03:00:17 PM UTC | 0 ⭐ | 506 👁️ | Never ⏰ | []
C |

1.21 KB

|

None

|

0 👍

/

0 👎

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(int argc, char *argv[]){
   // argc keeps count of all of the command line arguments
   // FOR EXAMPLE:
   // ./a.out hello there >>> argc = 3
   // ./a.out here are more arguments >>> argc = 5
   // ./a.out project.c >>> argc = 2
 
   // argv is a 2D array of strings, with the ./a.out (or ./a.exe) always at index 0
   // FOR EXAMPLE:
   // ./a.out hello there >>> argv = ["./a.out", "hello", "there"]
   // ./a.out here are more arguments >>> argv = ["./a.out", "here", "are", "more", "arguments"]
   // ./a.out 123 abc >>> argc = ["./a.out", "123", "abc"];
   // Notice: even numbers count as strings when coming from the command line
   // Use atoi() [meaning convert an alphanumeric string/char to an integer] if need be 
 
   printf("Looping through argv...\n");
 
   for (int i = 0; i < argc; i++){
      printf("argv[%d]: %s\n", i, argv[i]);
   }
 
printf("\n\n\n------------\n\n\n");
 
   printf("Looping through letters...\n");
   for (int i = 0; i < argc; i++){
      for(int j = 0; j<strlen(argv[i]);j++){
         printf("argv[%d][%d]: %c\n", i,j,argv[i][j]);
      }
      printf("\n------------\n");
   }
 
 
   return 0;
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎