Hi,
I've got problem with method ignore from cin.
This is my code:

void _name()
{
	string name;
	char ch = 0;
	bool name_accepted = false;
	cout << "Enter your name: " << endl;
	while (!name_accepted)
	{
		while (ch = cin.get())
		{
			//cin.
			if (isalnum(ch) || isspace(ch) || ispunct(ch)) //construct name
			{
				name += ch;
				if ((ch == '\n') && cin && (name == ""))
				{
					name = "UNNAMED";
				}
				if ((ch == '\n') && cin && (name != ""))
				{
					name_accepted = true;
				}
			}
			else
			{
				cerr << "Bad input. Try again." << endl;
				cin.clear(ios_base::failbit); //set to fail
			}


			if (!cin)
			{
				name = "";
				ch = 0;
				cin.ignore(256);
				//cin.seekg(0);
				//cin >> _dump;
				cin.clear();
			}
		}
		if (!cin)
		{
			//throw new _Exit();
			cerr << "Bad input. Try again." << endl;
			name = "";
			ch = 0;
			cin.ignore(256);
			//cin.seekg(0);
			//cin >> _dump;
			cin.clear();
		}

	}

}

but when I enter :
a^A^Atom (letter a, ctrl+A, ctrl+A, t, o,m), it catches correctly error but ignore seems to ignore just one sign instead of ignoring all of them. Hope someone will help with this. Thank you.

Recommended Answers

All 4 Replies

Your inner loop does not account for the name being accepted and there is no way to break out of it without somehow signaling a character that has a value of 0. This will work better:

while (!name_accepted && cin.get(ch))

Otherwise the code works fine.

Tom Gunn,
it doesn't work correctly. Try input (letter a, ctrl+A, ctrl+A, t, o,m). In my opinion it should discard everything after encountering first "bad" character but it doesn't do that for reason that I don't know and would like to know. cin.ignore(256) seems to throw away just one character instead of "all" of them. Any reason why?

The order of cin.clear() and cin.ignore() is backward. cin.ignore() is just as much a read as cin.get() , so if the stream is in an error state, nothing will be read. The code needs to clear first, then ignore:

if (!cin)
{
    name.clear();
    cin.clear();
    cin.ignore(256, '\n');
}

I also added '\n' to the call because the delimiter defaults to EOF. That turns cin.ignore() into a blocking read because it waits for up to 256 characters or EOF.

commented: Perfect! +19

Tom Gunn,
It's working this time. Thank you.

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.