您應該在使用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)測試是否相等(不是'==') 。 –
即使在修復字符串比較之後,如果您不傳遞它正在查找的兩個參數組合之一(因此它可能並不是不尋常的,它根本不會打印任何內容),您的程序將不會打印任何內容。最後,如果少於兩個參數傳遞給程序,它將表現出不可預測的行爲 - 可能會崩潰。 –
字符串上的'=='只是比較它們的地址,所以在你的情況下比較會失敗。你需要調用'strcmp'來比較實際的字符串。 –