Cを使用しているときに警告をオンにする必要があります。なぜこれが失敗するのかが分かります。あなたはクラン
gcc -Wall -std=c11 -pedantic goo.c
でそれをコンパイルするためにこれを使用した場合は、これらのエラーを持っているでしょう:
goo.c:19:13: warning: result of comparison against a string literal is unspecified (use strncmp instead) [-Wstring-compare]
if (av[1] == "stop" && av[2] == "A")
^~~~~~~
goo.c:19:32: warning: result of comparison against a string literal is unspecified (use strncmp instead) [-Wstring-compare]
if (av[1] == "stop" && av[2] == "A")
^~~~
goo.c:24:13: warning: result of comparison against a string literal is unspecified (use strncmp instead) [-Wstring-compare]
if (av[1] == "start" && av[2] == "^Q")
^~~~~~~~
goo.c:24:33: warning: result of comparison against a string literal is unspecified (use strncmp instead) [-Wstring-compare]
if (av[1] == "start" && av[2] == "^Q")
あなたは文字列比較関数を使用して文字列を比較する必要があります。 ==
を使用して文字列を比較することはできません。
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "termios.h"
int main (int ac, char* av[])
{
struct termios ttyinfo;
int result;
result = tcgetattr(0, &ttyinfo);
if (result == -1) {
perror("cannot get params about stdin");
exit (1);
}
if(ac > 2) {
if (strcmp(av[1], "stop") == 0 && strcmp(av[2], "A") == 0) {
printf ("Stop: ^%c\n", ttyinfo.c_cc[VSTOP] - 19 + 'A');
}
if (strcmp(av[1], "start") == 0 && strcmp(av[2], "^Q") == 0) {
printf ("Stop: ^%c\n", ttyinfo.c_cc[VSTOP] - 3 + 'A');
}
}
else {
printf("Need two arguments\n");
}
return 0;
}
がstrncmp
とstrcmp
にまで読む代わりにこのような何かを試してみてください。特に、strncmp
がなぜstrcmp
よりも好ましいのかを知っていることを確認してください。
['strncmp'](http://en.cppreference.com/w/c/string/byte/strncmp)を使って等価性(' == 'ではなく)をテストするので、' print'しません。 –
また、文字列の比較を行った後でも、探している引数の2つの組み合わせの1つを渡さないと、プログラムは何も印刷しません(何も印刷しないことが珍しくないかもしれません)。最後に、2つよりも少ない引数がプログラムに渡されると、予期せず動作します。おそらくクラッシュします。 –
'=='文字列上では単にアドレスを比較するので、あなたの場合は比較が失敗します。実際の文字列を比較するには、 'strcmp'を呼び出す必要があります。 –