第13.7 小节代码 核对行星的名字
//This is a comment
//Author:King
//Time:2020/12/9
//Reference:C Programming:A Modern Approach,Second Edition
/*******************************************************************************
13.7 小节代码 核对行星的名字 ,本程序涉及到字符串数组和命令行的使用。程序执行后
在命令行中输入planet xxxx yyyy等,程序会检查输入的字符串是否为行星的名字并排序
********************************************************************************/
#include <stdio.h>
#include <string.h>
//#include <stdbool.h> // C99 only
//#include <time.h>
//#include <stdlib.h>
#define NUM_PLANETS 9
/*主函数*/
//argc是命令行参数的数量,包括程序本身,argv是指向命令行参数(字符串)的指针数组,这些命令行参数以字符串的形式存储
int main(int argc, char *argv[])
{
char *planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}; //这个数组可以理解为数组的元素是指向字符串的指针
int i, j;
for(i = 1; i < argc; i++) //这里i从1开始表示跳过0,也就是不对比命令行参数的第一个参数(程序名)
{
for(j = 0; j < NUM_PLANETS; j++)
{
if(strcmp(argv[i], planets[j]) == 0)
{
printf("%s is planet %d\n", argv[i], j + 1);
break;
}
}
if(j == NUM_PLANETS)
printf("%s is not planet\n", argv[i]);
}
system("pause"); //加入该函数后可以使得产生的exe单独运行,不会发生闪退。也可以加入其它函数使得main函数无法返回即可。如while(1)、getchar() 等
return 0;
}