I am new to programming and I am studying arrays and pointers but I have come across the issue of the buffer and I would like to clear up two doubts:
- What is the use of clearing the buffer?
- How is the buffer cleared?
I have seen that the function is often used cin.ignore()
but I really do not understand how it is used, if possible, give me some examples to know how and when it is used.
Suppose you have an application that, as things happen, asks the user questions...
In such a case, it would be important to clear the input buffer, because during the wait, the user could touch the keyboard unintentionally, and this accidental touch has remained in the buffer until the standard input (cin) is read.
It is a design decision, when you want to be (somewhat more) sure that it is a conscious decision of the user and therefore you do not accept the data in the buffer.
So before
cin >> opcion
you putcin.ignore(N)
, to forcefully discard N bytes from the input buffer.Finally, I'm not sure there is a portable solution to all platforms, this is the base. There are other more C++ style options.