Operators in if-else statement????

Feb 16, 2012 at 4:52am
I have to write a program that reads a phone number and validates it. I thought I had it but it seems I'm not using the 'OR' and 'AND' operators properly. Can someone steer me in the right direction please.

#include<iostream>
#include<string>

using namespace std;

int main()

{

string number;
int nonum;

cout << "Please enter a valid phone number with no dashes or spaces and I will format it for you: ";

cin >> number;

if ((number.length() != 10) || (number.length() != 11))

{
cout << "ERROR: A phone number is a sequence of 10 digits or a sequence of 11 digits starting with 1.\n" << endl << "Try again, genuis.\n" << endl;
}

else if ((number.length() == 10) && (number.substr(0, 1) == "0") || (number.substr(0, 1) == "1"))

{
cout << "ERROR: A local phone number can not begin with 0 or 1.\n" << endl << "Try again, genius.\n" << endl;
}

else if ((number.length() == 11) && (number.substr(0, 1) != "1"))

{
cout << "ERROR: A long distance call must begin with 1.\n" << endl << "Try again, genuis.\n" << endl;
}

else if (nonum != string::npos)

{
cout << "A phone number consists of numerical digits only. There is a non-numerical digit in position " << nonum << endl << endl << "Try again, genuis.\n" << endl;
}

else if (number.substr(0, 1) == "1")

{
cout << "(" << number.substr(1, 3) << ") " << number.substr(4, 3) << "-" << number.substr(7, 4) << endl;
}

else

{
cout << "(" << number.substr(0, 3) << ") " << number.substr(3, 3) << "-" << number.substr(6, 4) << endl;
}

system ("pause");

return 0;

}
Feb 16, 2012 at 4:58am
Recheck where you are using your ||s. For example, on this line:

if ((number.length() != 10) || (number.length() != 11))

This if statement will always be entered. Can you figure out why?
Feb 16, 2012 at 5:45pm
Recheck where you are using your ||s. For example, on this line:

if ((number.length() != 10) || (number.length() != 11))

This if statement will always be entered. Can you figure out why?


Thanks firedraco for responding. I tried all last night to figure out that very issue. To me that line reads: if the length of string variable 'number' is not equal to 10 or 11... I really don't know where I'm going wrong.
Feb 16, 2012 at 6:05pm
|| returns true if at least one of the sides are true. There is no way both sides can be false (the length can't be 10 and 11 at the same time) so the expression must always be true.
Feb 16, 2012 at 6:43pm
Thanks Peter87! So I should replace '||' with '&&' and it would work?
Feb 16, 2012 at 6:48pm
Yes.
Feb 16, 2012 at 7:09pm
I get it now, thanks again!
Topic archived. No new replies allowed.