// Description: Illustrate the use of cin to lớn get input// và how khổng lồ recover from errors.#include using namespace std;int main(){ int input_var = 0; // Enter the bởi while loop và stay there until either // a non-numeric is entered, or -1 is entered. lưu ý that // cin will accept any integer, 4, 40, 400, etc. vì chưng { cout > input_var)) { cout What is the significance of cin.clear() and cin.ignore()? Why are the 10000 and parameters necessary?

c++ input đầu vào iostream cin Share Improve this question Follow edited Apr 3 “trăng tròn at 12:24


Ardent Coder 3,26999 gold badges1818 silver badges3939 bronze badges asked Feb 27 “11 at 5:17


JacKeownJacKeown 2,09055 gold badges2424 silver badges2929 bronze badges 1 Add a phản hồi |

4 Answers 4

Active Oldest Votes105The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), và then cin.ignore(10000, ”“) skips to lớn the next newline (khổng lồ ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up lớn 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

Bạn đang xem: Cin.ignore là gì

Đang xem: Cin.ignore là gì

Share Improve this answer Follow answered Feb 27 “11 at 5:36


Jeremiah WillcockJeremiah Willcock 27.1k55 gold badges6767 silver badges7474 bronze badges 6 31 If you want lớn use std::numeric_limits, make sure to lớn #include | Show 1 more comments 47You enter the

if (!(cin >> input_var))statement if an error occurs when taking the input đầu vào from cin. If an error occurs then an error flag is phối và future attempts to get đầu vào will fail. That”s why you need

cin.clear();khổng lồ get rid of the error flag. Also, the input đầu vào which failed will be sitting in what I assume is some sort of buffer.

Xem thêm: Spoofing Là Gì - Cách Phòng Chống Ip Spoofing (2021)

When you try lớn get đầu vào again, it will read the same input đầu vào in the buffer và it will fail again. That”s why you need

cin.ignore(10000,”“);It takes out 10000 characters from the buffer but stops if it encounters a newline (). The 10000 is just a generic large value.

Xem thêm: Cách Nhận Skin Lol Miện Phí 2017, Nhận Skin Lol Miện Phí 2017

Share Improve this answer Follow answered Feb 27 “11 at 5:44


flightflight 6,75344 gold badges2222 silver badges3030 bronze badges 1 Add a comment | 27Why bởi vì we use:

1) cin.ignore

2) cin.clear



1) To ignore (extract and discard) values that we don”t want on the stream

2) To clear the internal state of stream. After using cin.clear internal state is set again bachồng to lớn goodbit, which means that there are no “errors”.

Long version:

If something is put on “stream” (cin) then it must be taken from there. By “taken” we mean “used”, “removed”, “extracted” from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water