error trapping

i've looked at many forums still haven't found a proper answer to my question so i'm asking myself.
cin.clear
cin.ignore
how to use?
ALL any forum said is what it does i know what it does what i want is to know how to use it properly.
please use as many examples as you think neccesary i have always liked the examples i've seen on other subjects.
Well, you use them depending on your needs. There is literally hundresd of situations where you might need one of those functions.

Most common situation is to handle failed input:
1
2
int foo;
std::cin >> foo; 
if user inputs some garbage (like "asdwr"), nothing would be read, stream will be set in failed state and offending chunk of input will sit in input buffer.
You need to clear stream state (using clear member function) and remove incorrect input.
Two approaches:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::cin.clear(); //clear stream state
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //Clear all input till the end of current line
//If we will read integers in a loop. Then from line
// 5 2 0 adwasd 6 7
//only 5 2 0 will be read.

/*...*/

std::cin.clear(); //clear stream state
while(!isspace(std::cin.get()) && !std::cin.eof())
    ; //Skips whitespace delimited chunk of data
//If we will read integers in a loop. Then from line
// 5 2 0 adwasd 6 7
//5 2 0 6 7 will be read. 


Another common situation is when we need to use getline after formatted input:
1
2
std::cin >> foo;
std::getline(std::cin, bar);
As formatted input will leave endline symbols in input buffer, getline can read nothing or only whitespaces.
Solution is to start reading from first non-whitespace character:
1
2
3
4
5
std::cin >> foo;
std::getline(std::cin >> std::ws, bar);
//Handles well input like 
//6 Hello World
//It will read: 6, "Hello World" 
 
Sometimes you need to start exactly from the beginning of next line. In this case skipping unneeded input with .ignore() is used.
1
2
3
4
5
6
std::cin >> foo;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, bar);
//Only 6 will be read from line
//6 Hello World
//"Hello World" will be discarded and reading will start from the end of next line 
Topic archived. No new replies allowed.