查看输入缓冲区,并刷新 C 中的额外字符

发布于 2024-07-18 13:39:35 字数 350 浏览 5 评论 0原文

如果我想在 C 中接收一个字符输入,我将如何检查是否发送了额外的字符,如果是,我将如何清除它?

是否有一个函数的作用类似于 getc(stdin),但它不会提示用户输入字符,所以我可以只输入 while(getc(stdin)!=EOF); ? 或者一个函数来查看缓冲区中的下一个字符,如果它不返回 NULL (或那里的任何内容),我可以调用一个(另一个)函数来刷新标准输入?

编辑

所以现在, scanf 似乎正在做这个伎俩,但有没有办法让它读取整个字符串,直到换行符? 而不是到最近的空白? 我知道我可以将“%s %s %s”或其他内容放入格式字符串中,但我可以处理任意数量的空格吗?

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?

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?

Edit

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

在风中等你 2024-07-25 13:39:35

您无法刷新输入流。 如果这样做,您将调用未定义的行为。 你最好的选择是:

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;
}

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;
}

To use scanf magic:

#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;
}
世态炎凉 2024-07-25 13:39:35

您可以使用 getline 读取整行输入。

或者(为了回答您原来的问题),您可以在 stdin 上调用 selectpoll 来查看是否有其他字符需要读取。

You can use getline to read a whole line of input.

Alternatively (in response to your original question), you can call select or poll on stdin to see if there are additional characters to be read.

缺⑴份安定 2024-07-25 13:39:35

我今天遇到了类似的问题,我找到了一种似乎有效的方法。 我不知道你的具体情况,所以不知道是否适合你。

我正在编写一个例程,需要从键盘获取单个字符,并且它需要是三个特定击键(“1”、“2”或“3”)之一。 如果不是其中之一,程序需要发送错误消息并循环返回以进行另一次尝试。

问题是,除了 getchar() 返回我输入的字符之外,“Enter”击键(将击键发送到程序)也保存在输入缓冲区中。 然后,纠错循环中的 getchar() 工具返回该(非打印)换行符,进一步导致第二条错误消息(因为换行符既不是“1”,也不是“2”) ,也不是“3”。)

这个问题更加复杂,因为我有时会超前,而不是输入单个字符,而是输入这些选项之一将请求的文件名。 然后,缓冲区中有一整串不需要的字符,导致屏幕上滚动一长串错误消息。

不酷。

不过,似乎已经解决了这个问题:

c = getchar();  // get first char in line
while(getchar() != '\n') ; // discard rest of buffer

第一行是实际使用我输入的字符的行。 第二行处理输入缓冲区中剩余的任何残留物。 它只是创建一个循环,一次从输入缓冲区中提取一个字符。 语句循环时没有指定要发生的操作。 它只是读取一个字符,如果不是换行符,则返回下一个字符。 当它找到换行符时,循环结束并继续执行程序中的下一个业务顺序。

I had a similar problem today, and I found a way that seems to work. I don't know the details of your situation, so I don't know if it will work for you or not.

I'm writing a routine that needs to get a single character from the keyboard, and it needs to be one of three specific keystrokes (a '1', a '2', or a '3'). If it's not one of those, the program needs to send and error message and loop back for another try.

The problem is that in addition to the character I enter being returned by getchar(), the 'Enter' keystroke (which sends the keystroke to the program) is saved in an input buffer. That (non-printing) newline-character is then returned by the getchar() facility in the error-correction loop, resulting further in a second error message (since the newline-character is not either a '1', a '2', nor a '3'.)

The issue is further complicated because I sometimes get ahead of myself and instead of entering a single character, I'll enter the filename that one of these options will request. Then I have a whole string of unwanted characters in the buffer, resulting in a long list of error messages scrolling down the screen.

Not cool.

What seems to have fixed it, though, is the following:

c = getchar();  // get first char in line
while(getchar() != '\n') ; // discard rest of buffer

The first line is the one that actually uses the character I enter. The second line disposes of whatever residue remains in the input buffer. It simply creates a loop that pulls a character at a time from the input buffer. There's no action specified to take place while the statement is looping. It simply reads a character and, if it's not a newline, goes back for the next. When it finds a newline, the loop ends and it goes on to the next order of business in the program.

何以笙箫默 2024-07-25 13:39:35

我们可以创建一个函数来清除键盘缓冲区,如下所示:

#include <stdio.h>

void clear_buffer(){
   char b;
   //this loop take character by character in the keyboard buffer using 
   //getchar() function, it stop when the variable "b" was
   //enter key or EOF.
   while (((b = getchar()) != '\n') && (b != EOF));
}

int main()
{
    char input;
    //get the input. supposed to be one char!
    scanf("%c", &input); 
    //call the clearing function that clear the buffer of the keyboard 
    clear_buffer(); 
    printf("%c\n",input); //print out the first character input
    // to make sure that our function work fine, we have to get the
    // input into the "input" char variable one more time
    scanf("%c", &input); 
    clear_buffer();  
    printf("%c\n",input);
    return 0;
}

We can make a function to clear the keyboard buffer, like this:

#include <stdio.h>

void clear_buffer(){
   char b;
   //this loop take character by character in the keyboard buffer using 
   //getchar() function, it stop when the variable "b" was
   //enter key or EOF.
   while (((b = getchar()) != '\n') && (b != EOF));
}

int main()
{
    char input;
    //get the input. supposed to be one char!
    scanf("%c", &input); 
    //call the clearing function that clear the buffer of the keyboard 
    clear_buffer(); 
    printf("%c\n",input); //print out the first character input
    // to make sure that our function work fine, we have to get the
    // input into the "input" char variable one more time
    scanf("%c", &input); 
    clear_buffer();  
    printf("%c\n",input);
    return 0;
}
那伤。 2024-07-25 13:39:35

使用需要大量字符(超过 1 个,也许 256 个)的读取,并查看实际返回了多少个字符。 如果你得到不止一个,你就知道了; 如果你只得到一个,那就是所有可用的了。

你没有提到平台,这很快就会变得非常棘手。 例如,在 Unix (Linux) 上,正常机制将返回一行数据 - 可能是您要查找的一个字符和一个换行符。 或者,您可能说服用户输入 ^D(默认)来发送前面的字符。 或者,您可能使用控制功能将终端置于原始模式(如 viemacs 等程序所做的)。

在 Windows 上,我不太确定——我认为有一个 getch() 函数可以满足您的需要。

Use a read that will take a lot of characters (more than 1, maybe 256), and see how many are actually returned. If you get more than one, you know; if you only get one, that's all there were available.

You don't mention platform, and this gets quite tricky quite rapidly. For example, on Unix (Linux), the normal mechanism will return a line of data - probably the one character you were after and a newline. Or maybe you persuade your user to type ^D (default) to send the preceding character. Or maybe you use control functions to put the terminal into raw mode (like programs such as vi and emacs do).

On Windows, I'm not so sure -- I think there is a getch() function that does what you need.

好多鱼好多余 2024-07-25 13:39:35

为什么不使用 scanf 而不是 getc,通过使用 scanf 你可以得到整个字符串。

Why don't you use scanf instead of getc, by using scanf u can get the whole string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文