Gistrec

Understanding argc & argv [taking in command line arguments]

Apr 8th, 2018
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main(int argc, char *argv[]){
  6.    // argc keeps count of all of the command line arguments
  7.    // FOR EXAMPLE:
  8.    // ./a.out hello there >>> argc = 3
  9.    // ./a.out here are more arguments >>> argc = 5
  10.    // ./a.out project.c >>> argc = 2
  11.  
  12.    // argv is a 2D array of strings, with the ./a.out (or ./a.exe) always at index 0
  13.    // FOR EXAMPLE:
  14.    // ./a.out hello there >>> argv = ["./a.out", "hello", "there"]
  15.    // ./a.out here are more arguments >>> argv = ["./a.out", "here", "are", "more", "arguments"]
  16.    // ./a.out 123 abc >>> argc = ["./a.out", "123", "abc"];
  17.    // Notice: even numbers count as strings when coming from the command line
  18.    // Use atoi() [meaning convert an alphanumeric string/char to an integer] if need be
  19.  
  20.    printf("Looping through argv...\n");
  21.  
  22.    for (int i = 0; i < argc; i++){
  23.       printf("argv[%d]: %s\n", i, argv[i]);
  24.    }
  25.  
  26. printf("\n\n\n------------\n\n\n");
  27.  
  28.    printf("Looping through letters...\n");
  29.    for (int i = 0; i < argc; i++){
  30.       for(int j = 0; j<strlen(argv[i]);j++){
  31.          printf("argv[%d][%d]: %c\n", i,j,argv[i][j]);
  32.       }
  33.       printf("\n------------\n");
  34.    }
  35.  
  36.  
  37.    return 0;
  38. }
Add Comment
Please, Sign In to add comment