+ 1

Hey! I want to ask a question that is what is the purpose of using cin.ignore() in C++? Like when or why to use it in code.

12th Jun 2018, 5:08 PM
Sana Fatima
2 Antworten
+ 1
cin.ignore() is a predefined function which ignores/clears one or more characters from the input buffer. Pre-requisites: 1. The cin treats a white space i.e  " "  ,   "\t"   , "\n"   as delimiter character. 2. When you read anything from the standard input device, keyboard here, it firstly goes into the input buffer. The input buffer is a location that holds all incoming information before it continues to the CPU for processing. The Problem: 1. Suppose, you want to read a 'string' from the user. char myname[10]; 2. You somehow end up using cin, instead of cin.getline() cin>>myname; 3. I type "ABC", and then press Enter key. it takes up ABC and treats the following "\n"as delimeter. As a result, "\n" is not read and it remains in the input buffer. 4. So here, cin.ignore() will ignore these unread characters that remained in the input buffer.
13th Jun 2018, 1:11 PM
C.Gowthami
C.Gowthami - avatar
+ 1
Thank you so much! 🙂 C.Gowthami
14th Jun 2018, 6:07 AM
Sana Fatima