ignore function

Can anyone explain me what is "cin.ignore" is used for in a vary dumb way please? and when I'm supposed to use it
thanks!
Hello unkinkedash,

I will give it a try.

The first thing you need to understand is the when tying something on the keyboard does not put what you type directly into a variable,, butt into a buffer, normally refereed as the input buffer.

Depending on what you use to input into a variable will determine how much of the input buffer is extracted. using std::cin >> aVariable;. Is known as formatted input. Meaning that there is some type checking on the input, e.g., "aVariable" defined as an "int" will only accept numbers and a letter will cause the input to fail. The type checking works best with numeric variables.

The draw back to std::cin >> aVariable; is that it will extract from the input buffer up to the first white space or new line (\n) that is encountered, but will leave the "\n" in the buffer. Normally this is not a problem unless you follow a std::cin >> aVariablle; with a std::getline(std::cin, line);. Because the "getline" will extract everything from the buffer including the "\n". So if there is a "\n" in the input buffer the "getline" will extract it from the input buffer and move on to the next line of code.

The std::cin.ignore(); may work, but is is more common to use std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>. This would be used after a std::cin >> aVariable; or before std::getline(std::cin, line); to clear the input buffer.

The above is the more common use of "std::cin.ignore(...);". The other is at the end of main just before the return to keep the console window open until you press enter and the program ends and the console window closes. It could also be used as a pause anywhere in a program.

The best use of "std::cin.ignore(...);" is to clear the input buffer when needed.

Hope that helps,

Andy
Topic archived. No new replies allowed.