【问题标题】:control c causes printing of garbage控制 c 导致打印垃圾
【发布时间】:2014-04-27 16:52:04
【问题描述】:

我正在制作一个小测试程序,它演示了一个简陋的控制台界面。

该程序是一个低于标准的典型 get-line,响应程序甚至不识别“退出”,并希望您通过按 control-c 强制退出。这是在 Mingw32 上完成的。

让我感到困惑的是,当按下控制 c 时。程序在退出前显示垃圾。

例如:

<client> Welcome to Concept Program.
<client> type h for help menu.
<you> meep
<client> 'meep' is not a recognized command.
<you> *ctrl-c*
<you> <client> 'meep' is not a recognized command.

这个程序的代码是:

#include <stdio.h>

int main(int argc, char **argv)
{
    puts("<client> Welcome to Concept Program.");
    puts("<client> type h for help menu.");

    while (1) {
        char msg[200];
        printf("<you> ");
        gets(msg);
        if (strcmp(msg, "h") == 0) {
            puts("<client>");
            puts("-help menu-");
            puts("h: shows this menu");
            puts("-----------");
        } else {
            printf("<client>'%s' is not a recognized command.\n", msg);
        }
    }

    return 0;
}

我想知道在这种情况下如何阻止它打印垃圾,如果可能的话,解释一下为什么会发生这种情况。

我知道这是一个愚蠢的问题,但感谢任何帮助!

【问题讨论】:

  • 我的印象是您显示的输出不是由您提供的代码产生的。
  • 我在您的示例输出中没有看到垃圾值。
  • 不要使用gets(),它不再是C,即使它是危险的坏。
  • 代码也错过了原型strcmp()。
  • "Ctrl+C" 没有得到gets 的进程;它发送一个(较低级别的)signal,这可能最终会弄乱你的输出。尝试按照stackoverflow.com/questions/3189650/… 中的建议拦截此信号

标签: c mingw


【解决方案1】:

这样写,你需要检查 fgets 的返回值,如果按下 ctrl-c 会返回 NULL。

   while (1) {
        char msg[200];
        printf("<you> ");
        if (fgets(msg,sizeof(msg),stdin) != NULL)
        {
          if (strcmp(msg, "h") == 0) 
          {
              puts("<client>");
              puts("-help menu-");
              puts("h: shows this menu");
              puts("-----------");
          } 
          else 
          {
              printf("<client>'%s' is not a recognized command.\n", msg);
          }
        }
    }

【讨论】:

  • 我尝试对 fgets 做空检查,但仍然打印垃圾,例如最后的“”。
  • 奇怪,因为我尝试了 mingw 中的代码,它似乎可以工作。你在linux上吗?
  • 我在 windows 上运行它。
  • 我也在 Windows 上运行它。奇怪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 2017-07-21
  • 2013-12-23
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
相关资源
最近更新 更多