2016-05-17 154 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