This dude is probably from Penn State taking
either CMPSC 201c or CSE 103 (or variants of the same
course)
But anyway... here's what I did when I took that
class
Code:
//[MOONWALKER]
//Lab assignment 13
#include <iostream>
#include <string>
using namespace std;
//precondition: a sting message is passed
//postcondition: displays an error and terminates the program
void PhoneError(string message)
{
//showing the error message intended
cout << "Your call cannot be completed because: " << endl;
cout << message << endl;
//exiting the program
exit(1);
}
//precondition: a sting is passed
//postcondition: nothing happens if it is valid. otherwise program terminates
void CheckValidity(string aString)
{
int i;
//if the size is other than 7 or 11
if ( aString.size() != 11 && aString.size() != 7)
{
PhoneError("A phone number should have 7 or 11 characters");
}
//if the number is 11 digits and doesn't start with 1
else if (aString.size() == 11 && aString.substr(0,1) != "1")
{
PhoneError("A long distance call must begin with 1");
}
//if the number is 7 digits and starts with a 0 or a 1
else if (aString.size() == 7 && aString.substr(0,1) == "1" || aString.substr(0,1) == "0")
{
PhoneError("A call cannot start with a 0 or a 1");
}
//checking if the number contains any illegal characters
for (i = 0; i < aString.size(); i++)
{
if (aString.substr(i, 1) < "0" || aString.substr(i, 1) > "9")
{
PhoneError("A phone number must consist of all digits");
}
}
}
int main()
{
//setting up variables
string phonenumber, newformat;
//taking the input
cout << "Enter a phone number: ";
cin >> phonenumber;
//checking the validity of the input using the CheckValidity function
CheckValidity(phonenumber);
//showing the output based on the size of the given number
if (phonenumber.size() == 11)
{
newformat = "(" + phonenumber.substr(1, 3) + ")-" + phonenumber.substr(4, 3) + "-" + phonenumber.substr(7, 4);
}
else if(phonenumber.size() == 7)
{
newformat = phonenumber.substr(0,3)+ "-" + phonenumber.substr(3, 4);
}
//printing the number as desired
cout << newformat << endl;
return 0;
}