コマンドラインから名前を受け取って、あいさつを表示するプログラムを作りました。プログラムを実行すると期待どおりに表示されましたが、あと少し改善できる部分があります。
![](/wp-content/include/images/avatar/teacher/5.png)
どこが改善できるか分かりますか?
main.c
#include <stdio.h>
void Greet(const char *pName) {
printf("Hello, %s!\n", pName);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
puts("No input.");
return 1; /* 失敗 */
}
for (int i=1; i<argc; i++) {
Greet(argv[i]);
}
return 0; /* 成功 */
}
実行結果
↓コマンドライン引数が「Leo Yuki」の場合:
Hello, Leo!
Hello, Yuki!
↓コマンドライン引数なしの場合:
No input.
![](/wp-content/include/images/avatar/student/6.png)
これは、第04問の変形ですね。
![](/wp-content/include/images/avatar/teacher/4.png)
そうね。コマンドライン引数で1つ以上名前を指定すると……
![](/wp-content/include/images/avatar/student/8.png)
ひとりひとりの名前であいさつを表示します!
![](/wp-content/include/images/avatar/teacher/5.png)
それじゃあ、名前を1つも指定しなかった場合は……
![](/wp-content/include/images/avatar/student/10.png)
「失敗」になって、プログラムを終了します!
![](/wp-content/include/images/avatar/teacher/3.png)
あいさつを表示できれば「成功」、できなければ「失敗」ということね。
![](/wp-content/include/images/avatar/student/7.png)
ちゃんと表示されてるのに、まだ改善できるところなんてあるのかなぁ。
![](/wp-content/include/images/avatar/teacher/7.png)
これまでに出てきたプログラムと見比べてみましょう。