I was tried to debug to find an explanation to this but i still don't really understand the concept. Here goes.

//pass in value 
//973 456.2 77F
//973 456.2 77F

#include<iostream>
using namespace std;

int main()
{
	char letter;
	int n;
	float m;
	
	cin>> m;
	cin.clear ();
	cin.ignore (200, '\n');
	cin>> letter>> n>> n;
	cout<< letter<< m<< n<< endl; //pass out 9973456
	
}

I am stuck in how does cin.clear() and cin.ignore(200, '\n') work and does it really ignore 200 characters? If possible, a total explanation of how the whole snippet works will be desirable. Thanks again for spending time to look at my code. I welcome any suggestion and criticism. :)

INPUT-BUFFER: 973 456.2 77F NEWLINE 973 456.2 77F

1)	cin>> m;  //m = 973 
INPUT-BUFFER: 456.2 77F NEWLINE 973 456.2 77F

2)	cin.clear (); //clears the state bits
INPUT-BUFFER: 456.2 77F NEWLINE 973 456.2 77F

3)	cin.ignore (200, '\n');  //ignores 200 characters or until a new line is reached
INPUT-BUFFER: 973 456.2 77F

4)	cin>> letter>> n>> n;   //letter = '9' , n = 73 then n = 456

INPUT-BUFFER: [ is in a failed state I think not sure, sets the state bits ]

5) cout<< letter<< m<< n<< endl; //pass out 9973456

I am stuck in how does cin.clear() and cin.ignore(200, '\n') work

cin.clear() resets the error state of the cin object. So if any of cin.eof(), cin.fail(), or cin.bad() return true, they'll return false after calling cin.clear(). The reason you need to call cin.clear() is because until the error state is reset, you won't be allowed to do any input; all requests will fail:

#include <iostream>
 
using namespace std;
 
int main()
{
    // Force cin into an error state
    cin.setstate(ios::failbit);
 
    char ch;
 
    // Try to read from cin
    cout << (cin.get(ch) ? "It worked!" : "It failed!") << endl;
 
    // Reset the error state with cin.clear()
    cin.clear();
 
    // Try to read from cin again (you'll need to type something)
    cout << (cin.get(ch) ? "It worked!" : "It failed!") << endl;
}

does it really ignore 200 characters?

cin.ignore() essentially does this:

void my_ignore(int n, char stop)
{
    char ch;
    
    for (int i = 0; i < n; i++)
    {
        if (!cin.get(ch) || ch == stop)
        {
            break;
        }
    }
}

So your call to cin.ignore() reads and discards *up to* 200 characters. If there are fewer than 200 characters in the stream or there's an occurrence of the stop character, it will read and discard fewer than 200. But in your call 200 is the upper limit, it won't read more than that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.