繁体   English   中英

控制c导致打印垃圾

[英]control c causes printing of garbage

我正在编写一个小型测试程序,该程序演示了原始的控制台界面。

该程序是低于标准的典型get-line的响应程序,甚至无法识别“退出”,并且希望您通过按Ctrl-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;
}

我想知道在这种情况下如何阻止它打印垃圾,并尽可能解释这种情况的发生原因。

我知道这是一个愚蠢的问题,但我们会提供任何帮助!

而是这样写,您需要检查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);
          }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM