peek at input buffer, and flush extra characters i

2019-08-02 20:45发布

问题:

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?

回答1:

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


回答2:

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.



回答3:

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.



回答4:

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


回答5:

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.



回答6:

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