2016-05-17 151 views
-2
#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 (av[1] == "stop" && av[2] == "A") { 
    printf ("Stop: ^%c\n", ttyinfo.c_cc[VSTOP] - 19 + 'A'); 
    } 
    if (av[1] == "start" && av[2] == "^Q") { 
    printf ("Stop: ^%c\n", ttyinfo.c_cc[VSTOP] - 3 + 'A'); 
    } 
    return 0; 
} 

我在學習Linux,而且這段代碼是用C編寫的。使用命令行來顯示字符的變化。例如:./example stop A.但是,它不會在屏幕上顯示任何內容。爲什麼這個程序不打印出任何東西?

+0

由於您使用['strncmp'](http://en.cppreference.com/w/c/string/byte/strncmp)測試是否相等(不是'==') 。 –

+0

即使在修復字符串比較之後,如果您不傳遞它正在查找的兩個參數組合之一(因此它可能並不是不尋常的,它根本不會打印任何內容),您的程序將不會打印任何內容。最後,如果少於兩個參數傳遞給程序,它將表現出不可預測的行爲 - 可能會崩潰。 –

+0

字符串上的'=='只是比較它們的地址,所以在你的情況下比較會失敗。你需要調用'strcmp'來比較實際的字符串。 –

回答

3

您應該在使用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; 
} 

閱讀上strncmpstrcmp。特別是確保你知道爲什麼和當strncmpstrcmp更可取。

+0

我明白了,非常感謝! – Fed

+0

'gcc'是'clang'的別名? –

+0

@ElliottFrisch The mac。如果你想運行真正的gcc,你需要指定它。在我的系統上它是'gcc-5'。 [OS X 10.9 gcc鏈接到鐺](http://stackoverflow.com/questions/19535422/os-x-10-9-gcc-links-to-clang)。我使用兩者都是因爲你在實現中看到了一些有趣的差異,即不同的錯誤消息和不同的優化是最值得注意的兩個。 – Harry

相關問題