mirror of
https://github.com/hairrrrr/C-CrashCourse.git
synced 2026-02-10 22:16:10 +08:00
4-10
This commit is contained in:
27
code/practise/13 字符串/03 核对行星名字/planets.c
Normal file
27
code/practise/13 字符串/03 核对行星名字/planets.c
Normal file
@@ -0,0 +1,27 @@
|
||||
#include<stdio.h>
|
||||
#include<string.h>
|
||||
|
||||
#define NUM_PLANETS 9
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
|
||||
int i, j;
|
||||
char* planets[NUM_PLANETS] = {
|
||||
"Mercury", "Venus", "Earth",
|
||||
"Mars", "Jupiter", "Saturn",
|
||||
"Uranus", "Neptune", "Pluto"
|
||||
};
|
||||
|
||||
for (i = 1; i < argc; i++) {
|
||||
for (j = 0; j < NUM_PLANETS; j++)
|
||||
if (strcmp(argv[i], planets[j]) == 0) {
|
||||
printf("%s is a planet %d\n", argv[i], j + 1);
|
||||
break;
|
||||
}
|
||||
if (j == NUM_PLANETS)
|
||||
printf("%s is not a planet\n", argv[i]);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
// 程序会依次访问每个命令行参数,把它与 planets 中的字符串进行比较,直到找到匹配的名字或到了数组末尾才停止。
|
||||
21
code/practise/13 字符串/03 核对行星名字/readme.md
Normal file
21
code/practise/13 字符串/03 核对行星名字/readme.md
Normal file
@@ -0,0 +1,21 @@
|
||||
#### 程序:核对行星的名字
|
||||
|
||||
设计一个程序检查一系列字符串,从而找出那些字符串是行星的名字。执行程序时,用户把待测试的字符串放置在命令行中:
|
||||
|
||||
```c
|
||||
planet Mercury Aotoman Pluto Thebug Earth
|
||||
```
|
||||
|
||||
程序会指出每个字符串是否为行星名。如果是,程序还将显示行星的编号:
|
||||
|
||||
```c
|
||||
Mercury is a planet 1
|
||||
Aotoman is not a planet
|
||||
Pluto is a planet 9
|
||||
Thebug is not a planet
|
||||
Earth is a planet 3
|
||||
```
|
||||
|
||||
**注意:**命令行输入的第一个参数 planet 是 c 程序编译出的可执行程序名。一般一个叫 x.c 的程序编译后的可执行程序就叫做 x 。
|
||||
|
||||
我们命名这个 c 程序为 planet.c 所以编译后的可执行文件应该叫做 planet (在 Windows 上后缀应该为 .exe)
|
||||
Reference in New Issue
Block a user