Archived

This topic is now archived and is closed to further replies.

Catching errors from cin ...

This topic is 5118 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

It''s exam period, and I''m studying like .... anyway... I have a program that want the user to type their name, and I want some error control.
void ReadName( const char text[], char name[] )
{
	cout << text << ": ";
	cin.ignore( 10, ''\n'' );
	cin.getline( Name, 25 );

	while( cin.fail() )
	{
		cin.ignore( 10, ''\n'' );
		cin.clear();
		cout << "Error" << " type the name again: ";
		cin.getline( name, 25 );
	}
}
This is a what I have right now, and my brain is kinda slow for the moment. What I want is this: - If the user simply press enter without typing anyting, I want to trigger an error message. - If the user only type whitespace or other useless character I want to trigger an error message. I tried with strlen() , but that doesn''t work. And now I have gone empty for ideas, because I''m not sure how to catch those "errors".

Share this post


Link to post
Share on other sites
For the just hitting enter, I don''t think the inputing actually takes place if that happens. What I mean is, if you have a call to cin and they just hit enter, the program sits there wainting for some other kind of input.

As for the whitespace thing, a crappy solution would be to use the isspace() function from string.h. You could just loop through each character of the input checking it with the isspace function. Here''s where you can get some info on it. Just go to the Standard C String & Character portion for help with that function.

Hope it helps!

Share this post


Link to post
Share on other sites