【发布时间】: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/… 中的建议拦截此信号