I'm doing an exercise from C++ Primer
Rewrite your phone program so that it writes only the second and subsequent phone numbers for people with more than one phone number.
(The phone program simply recognises phone-numbers that have a certain format using a regular expression).
The chapter has been discussing using regex_replace
and the format flags to alter the format of the phone numbers entered in. The question is asking to ignore the first phone number entered and only format/print the second and subsequent. My input might look something like:
dave: 050 000 0020, (402)2031032, (999) 999-2222
and it should output
402.203.1032 999.999.2222
This is my solution:
#include <iostream>
#include <string>
#include <regex>
using namespace std;
using namespace regex_constants;
int main(){
string pattern = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
regex r(pattern);
//string firstFormat = "";
string secondFormat = "$2.$5.$7 ";
for(string line; getline(cin, line);){
unsigned counter = 0;
for(sregex_iterator b(line.begin(), line.end(), r), e; b != e; ++b)
if(++counter > 1) cout << (*b).format(secondFormat);
cout << endl;
// Below: iterates through twice, maybe not ideal
// string noFirst = regex_replace(line, r, firstFormat, format_first_only); //removes the first phone number
// cout << regex_replace(noFirst, r, secondFormat, format_no_copy) << endl;
}
}
However I am unhappy with the use of a counter to make sure I'm not processing the first match. It feels like there must be a more natural utility (like the format_first_only
flag that can be passed to format
, except in reverse) that makes it possible to ignore the first match? But I am struggling to find one.
The commented out solution seems a bit better except it requires a second iteration through the input.