From f7a471e3f435d7e6841a635adbc55768c7d73004 Mon Sep 17 00:00:00 2001 From: hairrrrr <781728963@qq.com> Date: Fri, 10 Apr 2020 17:56:09 +0800 Subject: [PATCH] 4-10 --- .../13 字符串/03 核对行星名字/planets.c | 27 +++++++++++++++++++ .../13 字符串/03 核对行星名字/readme.md | 21 +++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 code/practise/13 字符串/03 核对行星名字/planets.c create mode 100644 code/practise/13 字符串/03 核对行星名字/readme.md diff --git a/code/practise/13 字符串/03 核对行星名字/planets.c b/code/practise/13 字符串/03 核对行星名字/planets.c new file mode 100644 index 0000000..e357686 --- /dev/null +++ b/code/practise/13 字符串/03 核对行星名字/planets.c @@ -0,0 +1,27 @@ +#include +#include + +#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 中的字符串进行比较,直到找到匹配的名字或到了数组末尾才停止。 \ No newline at end of file diff --git a/code/practise/13 字符串/03 核对行星名字/readme.md b/code/practise/13 字符串/03 核对行星名字/readme.md new file mode 100644 index 0000000..7c5c805 --- /dev/null +++ b/code/practise/13 字符串/03 核对行星名字/readme.md @@ -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) \ No newline at end of file