我希望能够清除scanf读入的值。换句话说,我想删除scanf读入的值。
这是我的示例代码:
#include <stdio.h> #include <signal.h> #include <sys/time.h> volatile sig_atomic_t gotsignal; void handler(){ gotsignal = 1; } int main(){ struct sigaction sig; sig.sa_handler = handler; sig.sa_flags = 0; sigemptyset(&sig.sa_mask); alarm(5); sigaction(SIGALRM, &sig, NULL); int value; while(!gotsignal){ printf("Insert a value: \n"); scanf("%d", &value); } }
输出:
Insert a value: 5(dont press enter)[JPS@localhost c]$ 5 <-
是否有可能(如果是的话)如何清除5?
我一直在阅读有关terminal设置,fflushs,标准input,但我无法弄清楚。 请帮忙吗?
编辑:经过了很多trys我想我find了一些工作。 如果有人有这个问题,这为我工作(不知道它是否在其他系统和东西,有点新):
#include <stdio.h> #include <signal.h> #include <sys/time.h> #include <termios.h> #include <unistd.h> volatile sig_atomic_t gotsignal; void handler() { gotsignal = 1; } int main(){ struct sigaction sig; sig.sa_handler = handler; sig.sa_flags = 0; sigemptyset(&sig.sa_mask); alarm(5); sigaction(SIGALRM, &sig, NULL); int value; while(!gotsignal){ printf("Insert a value: \n"); scanf("%d", &value); } printf("\n"); tcflush(STDOUT_FILENO,TCIOFLUSH); <-important bit! return 0; }
输出:
Insert a value: 5 Insert a value: 5(no enter was pressed)! [JPS@localhost c]$ <- NO MORE NR 5! :D
你可以使用readline库。 但是我不确定明白你的意思是“清除5”。
最简单的例子可能是
// file testrl.c #include <readline/readline.h> #include <stdlib.h> int main () { char bufprompt[20]; char* lin = NULL; int cnt = 0; for (;;) { memset(bufprompt, 0, sizeof(bufprompt)); cnt++; snprintf(bufprompt, sizeof(bufprompt)-1, "%d: ", cnt); lin = readline(bufprompt); if (!lin) break; printf("you typed %s\n", lin); free (lin); } return 0; }
使用gcc -Wall -g testrl.c -o testrl -lreadline
编译上面的gcc -Wall -g testrl.c -o testrl -lreadline
另见这个问题
看到这些链接的好答案:
引用最有趣的:
没有标准的方法来丢弃stdio输入流中的未读字符。 一些供应商确实执行fflush,以便fflush(stdin)丢弃未读字符,尽管可移植程序不能依赖于此。 (stdio库的某些版本实现了fpurge或者fabort调用,它们可以做同样的事情,但这些也不是标准的)。注意,刷新stdio输入缓冲区也不一定是足够的:未读字符也可以在其他字符集中, OS级输入缓冲区。 如果你试图主动放弃输入(也许是因为预期会发出一个意外的提示来确认一个破坏性的行为,那么一个偶然输入的“y”可能是灾难性的), 你必须使用一个特定于系统的技术来检测提前输入的存在; 见问题19.1和19.2 。 请记住,如果您丢弃发生的输入太快,用户可能会感到沮丧。