Skip to content

Instantly share code, notes, and snippets.

@msikma
Created September 27, 2015 11:41
Show Gist options
  • Save msikma/209629e67033040b5b89 to your computer and use it in GitHub Desktop.
Save msikma/209629e67033040b5b89 to your computer and use it in GitHub Desktop.
Command line arguments
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int a, b, len, chr;
for (a = 1; a < argc; ++a) {
switch ((int)argv[a][0]) {
case '\\':
case '/':
case '-':
// Scan through the passed options.
len = strlen(argv[a]);
for (b = 1; b < len; ++b) {
chr = (int)argv[a][b];
switch (chr) {
case '?':
case 'h':
case 'H':
printf("help is on the way.\n");
break;
default:
printf("something else\n");
break;
}
}
break;
default:
printf("string: %s\n", argv[a]);
break;
}
}
return 0;
}
@msikma
Copy link
Author

msikma commented Sep 27, 2015

I tried to abstract the first switch to a function, but that doesn't work... what am I doing wrong?

int main(int argc, char *argv[])
{
    int a, b, len, chr;

    for (a = 1; a < argc; ++a) {
        printf("is option: %s\n", is_option(argv[a]));
        if (is_option(argv[a])) {
            // Scan through the passed options.
            len = strlen(argv[a]);
            for (b = 1; b < len; ++b) {
                chr = (int)argv[a][b];
                switch (chr) {
                    case '?':
                    case 'h':
                    case 'H':
                        printf("help is on the way.\n");
                        break;
                    default:
                        printf("something else\n");
                        break;
                }
            }
        }
        else {
            printf("string %s\n", argv[a]);
        }
    }
    return 0;
}

int is_option(int arg) {
    switch ((int)arg[0]) {
        case '\\':
        case '/':
        case '-':
            return 1;
        default:
            return 0;
    }
}
test.c: In function 'is_option':
test.c:8:21: error: subscripted value is neither array nor pointer nor vector
     switch ((int)arg[0]) {
                     ^
test.c: In function 'main':
test.c:23:45: warning: passing argument 1 of 'is_option' makes integer from pointer without a cast [-Wint-conversion]
         printf("is option: %s\n", is_option(argv[a]));
                                             ^
test.c:7:5: note: expected 'int' but argument is of type 'char *'
 int is_option(int arg) {
     ^
test.c:24:23: warning: passing argument 1 of 'is_option' makes integer from pointer without a cast [-Wint-conversion]
         if (is_option(argv[a])) {
                       ^
test.c:7:5: note: expected 'int' but argument is of type 'char *'
 int is_option(int arg) {
     ^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment