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;
}
{
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;
}
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.
|| 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.