偷看输入缓冲区,并刷新用C额外的字符 [英] peek at input buffer, and flush extra characters in C
问题描述
如果我想获得在C一个字符输入,我将如何检查,看看是否额外的字符被送到,如果是的话,我会怎么清除?
If I want to receive a one character input in C, how would I check to see if extra characters were sent, and if so, how would I clear that?
有没有这就像GETC(标准输入)功能,但不提示用户输入一个字符,这样我就可以只把而(GETC(标准输入)= EOF!);
?或者一个函数来在缓冲区中的下一个字符偷看,如果不返回NULL(或任何会在那里),我可以打电话(另)一个函数,它刷新标准输入?
Is there a function which acts like getc(stdin), but which doesn't prompt the user to enter a character, so I can just put while(getc(stdin)!=EOF);
? Or a function to peek at the next character in the buffer, and if it doesn't return NULL (or whatever would be there), I could call a(nother) function which flushes stdin?
所以,现在和scanf函数,似乎是在做的伎俩,但有没有办法得到它读全的字符串,直到换行?而不是最近的空白?我知道我可以只是把%s%s%S或任何入格式字符串,但我能处理的空间任意号码?
So right now, scanf seems to be doing the trick but is there a way to get it to read the whole string, up until the newline? Rather than to the nearest whitespace? I know I can just put "%s %s %s" or whatever into the format string but can I handle an arbitrary number of spaces?
推荐答案
您不能刷新输入流。如果你这样做,你会被调用未定义的行为。最好的办法是做:
You cannot flush the input stream. You will be invoking undefined behavior if you do. Your best bet is to do:
int main() {
int c = getchar();
while (getchar() != EOF);
return 0;
}
要使用 scanf函数
魔法:
#include <stdio.h>
#include <stdlib.h>
#define str(s) #s
#define xstr(s) str(s)
#define BUFSZ 256
int main() {
char buf[ BUFSZ + 1 ];
int rc = scanf("%" xstr(BUFSZ) "[^\n]%*[^\n]", buf);
if (!feof(stdin)) {
getchar();
}
while (rc == 1) {
printf("Your string is: %s\n", array);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getchar();
}
}
return 0;
}
这篇关于偷看输入缓冲区,并刷新用C额外的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!