I wrote a very basic program in C++ which asked the user to input a number and then a string. To my surprise, when running the program it never stopped to ask for the string. It just skipped over it. After doing some reading on StackOverflow, I found out that I needed to add a line that said:
cin.ignore(256, '\n');
before the line that gets the string input. Adding that fixed the problem and made the program work. My question is why does C++ need this cin.ignore()
line and how can I predict when I will need to use cin.ignore()
?
Here is the program I wrote:
#include <iostream> #include <string> using namespace std; int main() { double num; string mystr; cout << "Please enter a number: " << "\n"; cin >> num; cout << "Your number is: " << num << "\n"; cin.ignore(256, '\n'); // Why do I need this line? cout << "Please enter your name: \n"; getline (cin, mystr); cout << "So your name is " << mystr << "?\n"; cout << "Have a nice day. \n"; }
The cin. clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin. ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure).
The ignore() function is used to ignore or discard the number of characters in the stream up to the given delimiter. It is a member function of std::basic_istream and inherited from input stream classes. It takes the number of characters and the delimiter character as arguments.
You can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.
The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file.
Ignore is exactly what the name implies.
It doesn't "throw away" something you don't need instead, it ignores the amount of characters you specify when you call it, up to the char you specify as a breakpoint.
It works with both input and output buffers.
Essentially, for std::cin
statements you use ignore before you do a getline
call, because when a user inputs something with std::cin
, they hit enter and a '\n'
char gets into the cin
buffer. Then if you use getline
, it gets the newline char instead of the string you want. So you do a std::cin.ignore(1000,'\n')
and that should clear the buffer up to the string that you want. (The 1000 is put there to skip over a specific amount of chars before the specified break point, in this case, the \n newline character.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With