What is the purpose and how is the buffer cleaned?


I am an initiate in programming and I am studying arrays and pointers but I have run into the buffer issue and I would like to clear up two doubts:

  • What is the purpose of cleaning the buffer?
  • How is the buffer cleaned?

I have seen that the function cin.ignore() is usually used but I really do not understand how it is used, if possible, give me some examples to know how and when it is used.

asked by Malthael 27.08.2016 в 00:57

1 answer


Suppose you have an application that, as things go by, asks the user questions ...

int main() {
    std::cout << "Espere..." << std::endl;
    // aqui hace una (quiza larga) operacion y de repente pregunta
    std::cout << "Elija una opcion? [A,B,C]" << std::endl;    
    std::cin >> opcion;
    // y sigue con la operacion en base a la opcion 

In such a case, it would be important to clean the input buffer, because during the wait, the user could touch the keyboard without the intention, and this accidental touch has remained in the buffer until the standard input is read (cin) .

It is a design decision, when you want to be (something more) sure that it is a conscious decision of the user and therefore you do not accept the buffer data.

Then before cin >> opcion you set cin.ignore(N) , to discard N bytes from the input buffer, forcibly.

Finally, I'm not sure there is a portable solution to all platforms, this is the base. There are other more options of the c ++ style.

answered by 27.08.2016 / 03:06