Problems with exception handling.

I'm having trouble with a try/catch block I'm working with. Specifically, this piece:

1
2
3
4
5
6
7
8
9
string cycle;

cout << "Enter Cycle (AM/PM): ";
cin >> cycle;

if(notValidCycle(cycle))
{
    throw string("Not a valid cycle.");
}


Here's the notValidCycle() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
bool notValidCycle(string cyc)
{
	if(cyc.compare("AM") != 0)
		return true;
	else if(cyc.compare("PM") != 0)
		return true;
	else if(cyc.compare("am") != 0)
		return true;
	else if(cyc.compare("pm") != 0)
		return true;
	else
		return false;
}


At the prompt, I enter "PM" and it says "Not a valid cycle."
Is there something wrong with the way I'm comparing the strings?
closed account (3hM2Nwbp)
Read this and it'll all make sense. http://cplusplus.com/reference/string/string/compare/

Specifically

The member function returns 0 if all the characters in the compared contents compare equal.


You'll be able to fix your logic after reading as well.
Last edited on
I know. The function is SUPPOSED to return true if they don't match. That's why it returns true under those conditions.
Yeah, changing the return on those conditions to false corrected it... I'm not quite sure why...

My conditions were that if it wasn't true (if the user's string was not equal to one of those specified) that it would return true (meaning it's not valid) and would throw an exception... so what exactly did I do wrong? The compare function returns 0 if the two strings are equal, doesn't it?
Return Value
0 if the compared characters sequences are equal
Topic archived. No new replies allowed.