+ 1
What is the use of cin.get() and cin.ignore()?
How this functions work?
3 Answers
+ 5
When you perform input with cin, the data gets written from the console to an input buffer, which is further cleared into the data object indicated in the >> operation after appropriate conversion, since this input buffer reads only characters.
Thus, cin>>var will read some characters from the console, then convert to the var's type and save the data in it, clearing the number of assigned characters from the buffer.
Thus, when you perform cin>>var, and input the data, the reading stops only when \n (ENTER) is encountered, and this also gets written to the buffer, but is ignored.
Now, cin.get() is a special function used to read only a single character from this buffer (the last one). It will read any type of character, even '\n'. So if have the following code,
int var; char ch;
cin>>var; cin.get(ch);
The program will only read a character, as \n from the last operation is read by get(). This also affects getline(), and thats why you will have to use a delimiter.
But, if you wish to use these functions as they were before, you can use cin.ignore(). This function, is used to delete the last character from the buffer, or n characters from the buffer, till a \n is encountered and deletes that as well.
Thus, using the code above like this:
cin>>var;
cin.ignore();
cin.get();
will remove the \n encountered in cin>>var;
+ 18
When u use the get () function in console the ENTER is a separate character. After cin.get() most people use cin.ignore() or an other cin.get().
+ 5
Similarly, you may use cin.ignore() like this:
cin.ignore(8);
to remove the last 8 characters from the input buffer.