コマンドラインから受け取ったあいさつをオウム返しするプログラムを作りました。実行してみると、おおむね期待通りの表示が得られました。でも、このプログラムには大きな問題があります。
![](/wp-content/include/images/avatar/teacher/5.png)
どのように修正すべきか分かりますか?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char text[] = "hello";
if (strstr(argv[1], text) != 0) {
printf("You said %s.\n", argv[1]);
return EXIT_SUCCESS;
} else {
printf("Say %s.\n", text);
return EXIT_FAILURE;
}
}
期待される実行結果
↓コマンドライン引数に「hello」が含まれる場合(「hello-world」など):
You said hello-world.
↓コマンドライン引数に「hello」が含まれない場合:
Say hello.
![](/wp-content/include/images/avatar/student/2.png)
strstr()
って何をする関数ですか?
![](/wp-content/include/images/avatar/teacher/5.png)
これはね、1つ目の文字列に2つ目の文字列と同じものが含まれるかチェックする関数よ。
![](/wp-content/include/images/avatar/student/7.png)
ということは……。
argv[1]
はコマンドライン引数だから……。
![](/wp-content/include/images/avatar/teacher/3.png)
うんうん。
![](/wp-content/include/images/avatar/student/6.png)
コマンドライン引数に
hello
が含まれてたらオウム返しするんですね。
![](/wp-content/include/images/avatar/teacher/4.png)
そういうことね。
![](/wp-content/include/images/avatar/student/10.png)
で、それ以外のときは
Say hello.
と表示して、EXIT_FAILURE
を返すから失敗ってわけですね!
![](/wp-content/include/images/avatar/teacher/2.png)
そういうことなんだけど、ちゃんと動かないのよ。
![](/wp-content/include/images/avatar/teacher/7.png)
プログラムが期待どおりに動かない条件を考えてみましょう。