in (C++ please) Modify the code in section 23.7 to use a regex to recognize a So
ID: 3573934 • Letter: I
Question
in (C++ please)
Modify the code in section 23.7 to use a regex to recognize a
Social Security number or a UIN, with or without hyphens. A valid Social
Security number or UIN consists of three digits, an optional hyphen, two
digits, an optional hyphen, and four digits. Make each of the three numeric
fields a submatch (put it in parentheses) and also check the following
constraints:
If the second field is 00, it is a valid UIN.
Otherwise, it is a valid Social Security number unless:
One of the three fields is all zeroes.
The first field is 666 or any number in the range 9OO-999.
The number is
O42-68-4425,
O78-O5-112O,
123-45-6789,
111-11-1111,
222-22-2222,
333-33-3333,
444-44-4444,
555-55-5555,
777-77-7777,
888-88-8888,
999-99-9999, or
987-65-432x (where x is any digit O-9);
all these numbers are invalid (with or without hyphens).
Print the appropriate messages (valid UIN, invalid UIN, valid SSN, invalid SSN)
for each input until end of file. Note that more than one message may apply!
Name your program hw7pr2.cpp.
CODE OF SECTION 23.7 :
#include
#include
#include
#include
using namespa ce std;
int main()
{
ifstream in {"file.txt"}; // input file
if (!in) cerr << "no file ";
regex pat {R"(w{2}s*d{5}(–d{4})?)"}; // postal code pattern
int lineno = 0;
for (string line; getline(in,line); ) { // read input line into input buffer
++lineno;
smatch matches; // matched strings go he re
if (regex_search(line, matches, pat))
cout << lineno << ": " << matches[0] << ' ';
}
}
for (string line; getline(in,line); ) {
smatch matches;
if (regex_sea rch(line, matches, pat)) {
cout << lineno << ": " << matches[0] << ' '; // whole match
if (1 cout << " : " << matches[1] << ' '; // sub-match
}
}
Explanation / Answer
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include <regex>
#include <fstream>
#include <conio.h>
using namespace std;
int main()
{
std::ifstream in("C:\file.txt"); // input file
if (!in) cerr << "no file ";
std::regex pat("^(666|[900-999])-(00){2}-(?!0000)[0-9]{4}$");
std::smatch matches; // matched strings go here
int lineno = 0;
for (string line; getline(in,line); ) { // read input line into input buffer
++lineno;
if (std::regex_search(line, matches, pat))
std::cout << lineno << ": " << matches[0] << ' ';
getchar();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.