我正在尝试使用switch
和解析命令行中的参数getopt()
。结构很简单:我有一个makefile
,一个.c
和一个.h
文件。这是我第一次使用switch,所以我可能会犯一些基本错误。我已使用此链接作为切换
链接文本
和
链接文本的指南
如果您发现任何基本错误,请告诉我。
生成文件:
make:lunar
lunar: lunar.o
gcc -Wall -std=c99 -g -o lunar lunar.o -lm
lunar.o: lunar.c lunar.h
gcc -Wall -std=c99 -g -c lunar.c
clean:
-rm -f *.o lunar core
////////////////////////////////
月球.c
int main (int argc, char *argv[]){
int i;
int c = 0;
int gravity = 0;
int thrust = 0;
opterr = 0;
while ((c = getopt (argc, argv, "gtf:")) != -1)
switch (c){
case 'g':
gravity = argv[optind];
break;
case 't':
thrust = argv[optind];
break;
case 'f':
argument = argv[optind];
break;
case '?':
if (optopt == 'c')
fprintf(stderr, "Option -%c requires
an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option
`-%c'.\n", optopt);
else
fprintf (stderr, "Unknown option
character `\\x%x'.\n",
optopt);
return 1;
defult:
abort ();
}
printf ("gravity is %d and thrust is %d.\n",
gravity, thrust);
for (int index = optind ; index < argc ; index++ ){
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
}
//////////////////////////////
月球.h
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <assert.h>
#define MAX_WORD 256