CS157

CS157: Intro to C, Part II

Fall 2017

CLA

See this page as a slide show

Command-Line Arguments

CS157 CLA

CLA

% c11 -o getAvg getAvg.c
% ./getAvg 98 95 89 90 92 83
The average is 91.2
% ./getAvg 91.2 77 90 68 91
The average is 81.5

How to handle command-line arguments

#include <stdio.h>
int main(int argc, char *argv[ ]) {
    return 0;
}

Display the command line arguments

#include <stdio.h>
int main(int argc, char *argv[]) {
    printf("The %d args are:\n", argc);
    for (int i=0; i<argc; i++)
        printf("%d\t%s\n", i, argv[i]);
    return 0;
}
% ./a.out
The 1 arguments are:
0 a.out
% a.out 98 Cookie Monster rules
The 5 arguments are:
0 a.out
1 98
2 Cookie
3 Monster
4 rules

Example: getAvg.c

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
    int sum=0;
    for (int i=1; i<argc; i++)
        sum += atoi(argv[i]);
    printf("The average is: %f\n", sum / (argc - 1.0));
    return 0;
}
% gcc -o getAvg getAvg.c
% ./getAvg 98 95 89 90 92 83
The average is: 91.166667
% ./getAvg 77 90 68 91
The average is: 81.500000

Errors

#include <stdio.h>
int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <minimum> <maximum>\n", argv[0]);
        return 1;
    }
    // your code here
    return 0;
}

Handling arguments

Handling arguments

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    for (int i=1; i<argc; i++) {
        if (strcmp(argv[i], "-h") == 0) // do stuff for -h option
            printf("Help is on its way!\n");
        else if (strcmp(argv[i], "-n") == 0) {
            // now we know the next cmd-line arg is our number
            int num = atoi(argv[++i]);
            printf("Your lucky number is %d\n", num);
        }
        else {
            fprintf(stderr, "Unknown option \"%s\".\n", argv[i]);
            return 2;
        }
    }
    return 0;
}

Modified: 2015-06-10T21:43

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building