【问题标题】:Why don't this program print out anything?为什么这个程序不打印任何东西?
【发布时间】:2016-05-17 00:38:09
【问题描述】:
#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。但是,它不会在屏幕上显示任何内容。

【问题讨论】:

  • 它不是print,因为您使用strncmp 来测试是否相等(而不是==)。
  • 此外,即使您修复了字符串比较,如果您不将它正在寻找的两个参数组合之一传递给它,您的程序也不会打印任何内容(因此它可能并不罕见什么都不打印)。最后,如果传递给程序的参数少于两个,它将表现出不可预测的行为 - 可能会崩溃。
  • == 在字符串上只是比较它们的地址,所以在你的情况下比较会失败。您需要调用strcmp 来比较实际的字符串。

标签: c


【解决方案1】:

您应该在使用 C 时打开警告,并且您很可能会发现失败的原因。如果你用这个用 Clang 编译它

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 更可取。

【讨论】:

  • gccclang 的别名在什么平台上?
  • @ElliottFrisch Mac。如果你想运行真正的 gcc,你需要指定它。在我的系统上是gcc-5OS X 10.9 gcc links to clang。我使用这两种方法是因为您确实看到了一些有趣的实现差异,即不同的错误消息和不同的优化是最值得注意的两个。
猜你喜欢
  • 2013-04-06
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 2015-08-23
  • 2012-12-30
相关资源
最近更新 更多