B. Williams wrote:
Quote:
I have written some code to accept input and place this input at the
beginning or end of a list, but I need assistance including a class so that
it will allow input of a phone number that is properly formatted. I'll post
my code below. Thanks in advance.
#include<iostream>
#include<list>
#include<iterator>
#include<boost/regex.hpp>
#include<cassert>
using namespace std;
class PhoneNumber
{ public:
PhoneNumber(const string a, const string e, const string s):
area_code(a), exchange(e), station(s){};
string area_code, exchange, station;
};
ostream &operator<<(ostream &o, const PhoneNumber &n)
{
return o << "(" << n.area_code << ") "
<< n.exchange << "-" << n.station;
}
// This should probably be something fancier
//
http://en.wikipedia.org/wiki/North_A...Numbering_Plan
static const boost::regex
valid_ph("\\s*\\(?(\\d{3})\\)?\\s*[-.]?\\s*" // Area Code
"(\\d{3})\\s*[-.]?\\s*" // Exchange
"(\\d{4})\\s*"); // Station
void tests(void)
{
using namespace boost;
assert( regex_match("(800)555-1212" ,valid_ph));
assert( regex_match("800-555-1212 " ,valid_ph));
assert( regex_match("800.555.1212" ,valid_ph));
assert( regex_match("(800) 555 1212",valid_ph));
assert( regex_match("800 555 1212" ,valid_ph));
assert( regex_match("8005551212" ,valid_ph));
assert(not regex_match("800 555 12129" ,valid_ph));
assert(not regex_match(" 800 555 121" ,valid_ph));
assert(not regex_match("(foo) bar-quux",valid_ph));
}
int main(int argc, char* argv[])
{
string p;
list<PhoneNumberl;
boost::smatch m;
tests();
cout << "Enter Phone numbers (blank line to stop):\n";
while(true)
{
getline(cin,p);
if(not boost::regex_search(p,m,valid_ph)) break;
l.push_back(PhoneNumber (m[1].str(),m[2].str(),m[3].str()));
}
cout << "Phone numbers:\n";
copy(l.begin(),l.end(),ostream_iterator<PhoneNumbe r>(cout, "\n"));
return 0;
}