c - 如何清除 scanf 读取的内容?

标签 c linux stdin signals

我希望能够清除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?

我一直在阅读有关终端设置、fflushs、stdin 的内容,但我无法理解。有什么帮助吗?

编辑:经过多次尝试,我想我找到了一些有用的东西。如果有人遇到这个问题,这对我有用(不确定它是否适用于其他系统和东西,对此有点陌生):

#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

最佳答案

查看这些链接以获得好的答案:

引用最有趣的:

There is no standard way to discard unread characters from a stdio input stream. Some vendors do implement fflush so that fflush(stdin) discards unread characters, although portable programs cannot depend on this. (Some versions of the stdio library implement fpurge or fabort calls which do the same thing, but these aren't standard, either.) Note, too, that flushing stdio input buffers is not necessarily sufficient: unread characters can also accumulate in other, OS-level input buffers. If you're trying to actively discard input (perhaps in anticipation of issuing an unexpected prompt to confirm a destructive action, for which an accidentally-typed ``y'' could be disastrous), you'll have to use a system-specific technique to detect the presence of typed-ahead input; see questions 19.1 and 19.2. Keep in mind that users can become frustrated if you discard input that happened to be typed too quickly.

关于c - 如何清除 scanf 读取的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8286283/

相关文章:

linux - 使用 systemd 启动后触发 CURL 请求

ruby - 在 Ruby 中测试标准输入

c - 从 Windows gui 程序输出到命令行

c - 逐字节读取 pgm 文件会得到损坏的数据

c - 带有 strtod()/strtold() 的意外 endptr

linux - 使用 elasticbeanstalk 配置文件更改文件权限

c - 使用 add + shift 将 pcm16 转换为 pcm14

c - "Abort trap: 6"在Mac上运行C程序

c# - C# 中的事件驱动标准输入

eclipse 中的 c++ makefile 项目 - select() 在 stdin 中返回速度异常快