您的位置:首页 > 其它

练习17.21 使用本节中定义的valid函数重写8.3.2节(第289页)中的电话号码程序。

2017-04-12 15:51 405 查看
练习17.21 使用本节中定义的valid函数重写8.3.2节(第289页)中的电话号码程序。

解答: 主要就是写valid 来进行电话号码的正则表达式匹配。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <regex>

using namespace std;
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::ostringstream;
using std::string;
using std::vector;

struct PersonInfo {
string name;
vector<string> phones;
};

string format(const string &s) { return s; }

bool valid(const string &str)
{
string patten = "(\\()?(\\d{4})?(\\d{3})?([-. ]*)?(\\))?(\\d{8})?(\\d{7})";
regex r(patten);
smatch m;
regex_search(str, m, r);

if (m[1].matched) {
return m[4].matched && (m[2].matched || m[3].matched);
}
else {
return !m[4].matched && (!m[2].matched && !m[3].matched);
}
}

int main(int argc, char *argv[])
{
string line, word;
vector<PersonInfo> people;
istringstream record;
/**
if (argc != 2) {
cerr << "Please give the file name." << endl;
return -1;
}
ifstream in(argv[1]);
if (!in)
{
cerr << "can't open input file" << endl;
return -1;
}
*/
ifstream in("person_data.txt");
ofstream out("person_data_save2.txt");

while (getline(in, line)) {
PersonInfo info;
record.clear();
record.str(line);
record >> info.name;
while (record >> word)
info.phones.push_back(word);

people.push_back(info);

}

ostringstream os;
for (const auto &entry : people) {
ostringstream formatted, badNums;
for (const auto &nums : entry.phones) {
if (!valid(nums)) {
badNums << " " << nums;
}
else
formatted << " " << format(nums);
}
if (badNums.str().empty())
{
cout << endl;
os << "Formatted input: " << entry.name << " " << formatted.str() << endl;
}
else
cerr << "input error: " << entry.name << " invalid number(s) " << badNums.str() << endl;
}
cout << os.str() << endl;

return 0;
}


结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐