This is a simple program: pass user input via the main function in order to compute the range of a series of integers. However, the program is defaulting to the usage function. In other words, it does not seem to accept input from the command line.
The program executes, but somewhere along the way it reaches a condition where the usage message is printed to the terminal.
Here's the program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int range(int a[], int *n, int *rng){
//Declarations
int i; //Dummy variable
int min;
int max;
//Validate input
if(!a || !n || !rng || *n <= 0) return -1;
//Main execution
min = a[0];
max = a[0];
for(i=0; i<*n; i++){
if(a[i]<min)
min = a[i];
if(a[i]>max)
max = a[i];
}
*rng = max-min;
return 0;
}
void printUsage() {
printf("\nUsage:[-s <series of at least two integers>] [-h help].");
}
int main(int argc, char **argv){
//Declarations
int setInt[100];
int i; //Dummy index
int n; //Temp variable
int err;
int rng;
//Run some tests to determine validity of input
for(i=0; i<argc; i++){
//Is there at least some user input?
if(argc == 1){
printUsage();
return -1;
}
//Determine if the user requested usage
if(strcmp("-h", argv[i]) == 0){
printUsage();
return -1; //TRY REMOVING LATER TO SEE IF PROGRAM CAN KEPP RUNNING
}
//Determine if the user entered some data
else if(strcmp("-s", argv[i]) == 0){
//There must be at least TWO arguments after this call
if((i+1) == argc || (i+2) == argc){
printUsage();
return -1;
}
//Start another loop to fill an array of values the user entered
//Reuse i, but start at three to grap the first supposed integer
for(i=3; i < argc; i++){
err = sscanf(argv[i], "%d", &n);
if(err == 0) {//The input wasn't an integer
printUsage();
return -1;
}
else {
assert(err == 1);
setInt[i-3] = n; //Store the variable in an array
}
}
}
else{//unknown input
printUsage();
return -1;
}
//For bracket
}
//Call the function
printf("The range of values entered is %d.", rng);
range(setInt, &argc, &rng);
getchar();
getchar();
return 0;
//Main bracket
}
the problem is that you don't increment i before looking for -s change the line
else if(strcmp("-s", argv[i]) == 0){ //i is still zero, so argv[i] is the command entered
to
else if(strcmp("-s", argv[++i]) == 0){
(add ++ before the i) and it won't print usage.