这是一个简单的程序:通过main函数传递用户输入,以计算一系列整数的范围。但是,该程序默认使用功能。换句话说,它似乎不接受来自命令行的输入。
程序执行,但在某个地方它会达到将使用消息打印到终端的条件。
以下是该计划:
#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
}
答案 0 :(得分:0)
问题是你在寻找-s之前不要增加i 改变行
else if(strcmp("-s", argv[i]) == 0){ //i is still zero, so argv[i] is the command entered
到
else if(strcmp("-s", argv[++i]) == 0){
(在i之前添加++)并且它不会打印用法。